在我们进行数据传参访问的时候,HTTP协议的参数通常以键值对的形式出现,多个参数之间用 &分隔,但是如果值是中文或者是其他特殊字符的话,就要对其进行转码,不然可能会产生歧义,我们接下来就来看下如何对中文进行转码:
from urllib import parse
str = '中国'
print(parse.quote(str)) # 对中文进行编码
print(parse.unquote(parse.quote(str))) # 进行解码操作
# 输出结果:
# %E4%B8%AD%E5%9B%BD
# 中国
之前也有讲过,不同网站的编码格式也是会有差别的,这时候我们就需要根据他们的编码格式进行调整,先将文字转换为网站相同的编码,然后再进行转码:
from urllib import parse
str = '中国'
print(str)
print(parse.quote(str.encode('gbk')))
print(parse.quote(str.encode('utf-8')))
# 输出结果:
# 中国
# %D6%D0%B9%FA
# %E4%B8%AD%E5%9B%BD
那么我们在编程的时候会经常看见encode和decode,他们之间分别代表什么呢?
str = '中国' # 我们需要进行编解码的字符
str1 = str.encode('gbk') # 我们设置编码格式为GBK
str2 = str.encode('utf-8') # 设置编码格式为utf-8
print(str1)
print(str2)
# 如果这里输出str2.decode('gbk')就会报错,因为编码格式不匹配
print(str2.decode('utf-8')) # 将字符解码输出
# 输出结果:
# b'\xd6\xd0\xb9\xfa'
# b'\xe4\xb8\xad\xe5\x9b\xbd'
# 中国