In php, we can use urlencode() and urldecode() function to encode or decode a url or string. However, how about encoding and decoding url or string in python. In this tutorial, we will introduce you how to encode and decode a url or string in python.
Encode a dictionary
We can use urllib.parse.urlencode() to encode a dictionary, which is common used when you plan to send some data to a url.
Here is an example
import urllib.parse #query string query = {'key':'C++','num':10} #encode query string query_encode = urllib.parse.urlencode(query, encoding='utf-8') print(query_encode)
Then we can encode a query dictionary {‘key’:’C++’,’num’:10} to key=C%2B%2B&num=10
Encode a string
Here is a string in a url.
key='C++ and Python'
To encode this string, we can do like this.
key_encode = urllib.parse.quote(key, encoding='utf-8') print(key_encode)
Then the encoding result is: C%2B%2B%20and%20Python
From the result, we can find characters + and empty space is encoded.
Decode a string
key_decode = urllib.parse.unquote(key_encode, encoding='utf-8') print(key_decode)
The decoding result is: C++ and Python
In summary, to encode and decode a url or string in python we can:
encode: use urllib.parse.quote()
decode: use urllib.parse.unquote()