python字符串乱码怎么办

字符串在python内部的表示是unicode编码。

因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。 

decode的作用是将其他编码的字符串转换成unicode编码,如string1.decode('utf-8'),表示将utf-8编码的字符串string1转换成unicode编码。 

encode的作用是将unicode编码转换成其他编码的字符串,如string2.encode('utf-8'),表示将unicode编码的字符串string2转换成utf-8编码。

如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断:

isinstance(string3, unicode)  #用来判断string3是否为unicode编码

用非unicode编码形式的string3来encode也会报错。

推荐学习《Python教程》!

来源:PY学习网:原文地址:https://www.py.cn/article.html

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » python字符串乱码怎么办