品易云推流 关闭
文章详情页
文章 > Python常见问题 > python字符串乱码怎么办

python字符串乱码怎么办

头像

silencement

2020-02-04 16:31:432252浏览 · 0收藏 · 0评论

字符串在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教程》!

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图