使用urllib.parse
模块中的quote
和unquote
函数
URL编码
quote
函数将字符串中的特殊字符转换为%
加上两个十六进制数字的形式
from urllib.parse import quote
original_string = "Hello, world! This is a test string with spaces."
# 对字符串进行URL编码
encoded_string = quote(original_string)
print(encoded_string)
# 输出: Hello%2C%20world%21%20This%20is%20a%20test%20string%20with%20spaces.
URL解码
unquote
函数将%
加上两个十六进制数字的形式转换回原始的特殊字符
from urllib.parse import unquote
encoded_string = "Hello%2C%20world%21%20This%20is%20a%20test%20string%20with%20spaces."
# 对字符串进行URL解码
decoded_string = unquote(encoded_string)
print(decoded_string)
# 输出: Hello, world! This is a test string with spaces.