Python-url encoding and decoding

Source: Internet
Author: User
Tags urlencode

First, why the URL encoding

The request format for URL with parameters is (for example): Http://www.baidu.com/s?k1=v1&k2=v2

When the request data is a dictionary, the database = {k1:v1, k2:v2}, and the parameter contains Chinese or? , = and other special symbols, by URL encoding, the data into a specific format k1=v1&k2=v2, and the Chinese and special symbols are encoded to avoid ambiguity

Second, URL encoding

1, UrlEncode ()

From urllib import parsefrom urllib Import requesturl = ' http://www.baidu.com/s? ' Dict1 ={' wd ': ' Baidu translator '}url_data = Parse.urlencode (Dict1) #unlencode () Convert dictionary {k1:v1,k2:v2} to K1=v1&k2=v2print (Url_data )             #url_data: Wd=%e7%99%be%e5%ba%a6%e7%bf%bb%e8%af%91data = Request.urlopen ((url+url_data)). Read () # Read URL response result data = Data.decode (' utf-8 ') #将响应结果用utf8编码print (data) url_org = Parse.unquote (url_data) #解码urlprint (url_org)              #url_org: wd= baidu translation str1 = ' haha haha ' str2 = parse.quote (str1)    #将字符串进行编码print (str2)                 #str2 =haha%e5%93%88%e5% 93%88STR3 = Parse.unquote (str2)  #解码字符串print (STR3)                 #str3 =haha haha

2, quote () and unquote ()

str1 = ' haha haha ' str2 = parse.quote (str1)   #quote () encode the string print (str2)                #str2 =HAHA%E5%93%88%E5%93%88STR3 = Parse.unquote (STR2) #解码字符串print (STR3)                #str3 =haha haha

Python-url encoding and decoding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.