How to use urlencode and urldecode in Python3?
In Python, you can achieve encoding and decoding operations using the urlencode and parse_qs functions in the urllib.parse library.
- The urlencode function is used to encode dictionary-type parameters into a URL formatted string. For example:
from urllib.parse import urlencode
params = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
query_string = urlencode(params)
print(query_string)
The output result is:
name=Alice&age=25&city=New+York
- The parse_qs function is used to decode a URL formatted string into dictionary form parameters. For example:
from urllib.parse import parse_qs
query_string = 'name=Alice&age=25&city=New+York'
params = parse_qs(query_string)
print(params)
The output result is:
{'name': ['Alice'], 'age': ['25'], 'city': ['New York']}
This allows for carrying out operations of url encoding and url decoding.