UrlEncode and UrlDecode in Python

Source: Internet
Author: User
Tags urlencode

UrlEncode and UrlDecode in Python

Posted on 2013/11/13 16:04:09 79983 people read

Category: Python

When the URL address contains Chinese, or the parameters are Chinese, this is quite normal, but the URL as a parameter to pass the time (the most common callback), you need to put some Chinese or even '/' to do the code conversion.

First, UrlEncode

The Urllib library has a urlencode function that converts a key-value pair such as key-value into the format we want, and returns a string such as a=1&b=2, such as:

>>> FromUrllibImportUrlEncode>>> Data={... A: ,...  ' name ' :  ' Warcraft '  }>>> print urlencode (data) a=test&amp ; name=%c4%a7%< span class= "n" >ca%de          

What if you only want to convert a string to UrlEncode? Urllib provides another function: quote ()

>>> from urllib import quote>>> quote(‘魔兽‘)‘%C4%A7%CA%DE‘
Second, UrlDecode

When the string after the UrlEncode is passed over, the acceptance will decode the--urldecode. Urllib provides unquote () This function, can not urldecode ()!

>>> from  urllib import unquote>>> unquote('%c4%a7 %ca%de '\xc4\xa7\xca\xde'>>> print unquote('%c4%a7% Ca%de ') warcraft               
Iii. Discussion

When doing urldecode, see unquote () This function output, is corresponding to the Chinese code in the GBK, in contrast to the results of quote () is not difficult to find, the so-called UrlEncode is the string interchange GBK code, and then replace the \x to%. If your terminal is UTF8 encoded, then to turn the results into UTF8 output, otherwise garbled.

Functions such as UrlEncode (), UrlDecode () can be customized or rewritten according to the actual situation.

UrlEncode and UrlDecode in Python

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.