Python rookie Promotion one----UrlEncode and unquote

Source: Internet
Author: User
Tags urlencode

When the URL address contains Chinese or "/", this is required for UrlEncode encoding conversion.

First, UrlEncode

The UrlEncode parameter is a dictionary that converts key-value pairs such as key-value into the format we want. If you're using Python2.*,urlencode in Urllib.urlencode. If you're using Python3,urlencode in Urllib.parse.urlencode,

For example

Import urllib.parsedata={"name": "Wang Nima", "Age": "/", "addr": "ABCdef"}print (Urllib.parse.urlencode (data))
Output to

addr=abcdef&name=%e7%8e%8b%e5%b0%bc%e7%8e%9b&age=%2f
What if you only want to convert a string to UrlEncode? Urllib provides another function: quote ()
Print (Urllib.parse.quote ("Hahaha Hello! "))
Output to

hahaha%e4%bd%a0%e5%a5%bd%e5%95%8a%ef%bc%81

Second, unquotewhen the string after the UrlEncode is passed over, the acceptance will decode the--urldecode. Urllib provides unquote () This function, can not urldecode ()!
Import  urllib.parsedata={"name": "Wang Nima", "Age": "/", "addr": "ABCdef"}print (Urllib.parse.urlencode (data)) print ( Urllib.parse.quote ("Hahaha Hello!" ")) Print (Urllib.parse.unquote (" hahaha%e4%bd%a0%e5%a5%bd%e5%95%8a%ef%bc%81 "))
Output

addr=abcdef&name=%e7%8e%8b%e5%b0%bc%e7%8e%9b&age=%2fhahaha%e4%bd%a0%e5%a5%bd%e5%95%8a%ef%bc% 81hahaha Hello!

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.


Python rookie Promotion one----UrlEncode and unquote

Related Article

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.