在用python进行web开发的时候,当url中含有中文,那么传递到后台服务器的会是编码过的url,我们可以用python3把编码后的文本转化成我们可以识别的内容。如下操作:
import urllib
test_str = "哈哈哈"
print(test_str)
new = urllib.parse.quote(test_str)
print(new)
old = urllib.parse.unquote(new)
print(old)
运行代码,执行结果如下:
哈哈哈
%E5%93%88%E5%93%88%E5%93%88
哈哈哈
中间的%E5%93%88%E5%93%88%E5%93%88
就是经过url编码后的内容。
利用pycharm开发工具,我们可以看一下quote编码函数和unquote解码函数的构成。
关于quote函数:
def quote(string, safe='/', encoding=None, errors=None):
if isinstance(string, str):
if not string:
return string
if encoding is None:
encoding = 'utf-8'
if errors is None:
errors = 'strict'
string = string.encode(encoding, errors)
else:
if encoding is not None:
raise TypeError("quote() doesn't support 'encoding' for bytes")
if errors is not None:
raise TypeError("quote() doesn't support 'errors' for bytes")
return quote_from_bytes(string, safe)
我们可以看到文本的默认编码方式是utf-8编码,我们可以更换成另一种编码方式来看一下输出结果
test_str = "哈哈哈"
print(test_str)
new = urllib.parse.quote(test_str, encoding="gbk")
print(new)
old = urllib.parse.unquote(new, encoding="gbk")
print(old)
输出结果:
哈哈哈
%B9%FE%B9%FE%B9%FE
哈哈哈
根据结果也可以了解到urf-8编码一个汉字被编为3个百分号开头的字符串,而gbk编码一个汉字被编为2个百分号开头的字符串。unqoute也是同样的道理,故不再赘述。