Python中字符串编码的问题

Python fireling 6751℃ 0评论

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

比如从文件读入utf-8编码格式的字符串s,

s.decode("utf-8", "ignore").encode("gbk", "ignore") # 先由utf-8转为unicode,再由unicode转为gbk,ignore表示忽略非法字符

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(“gbk”, “ignore”),表示将gbk编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(“gbk”, “ignore”),表示将unicode编码的字符串str2转换成gbk编码。

因此,转码的时候一定要先搞明白,字符串str是什么编码,然后decode成unicode,然后再encode成其他编码。

代码中字符串的默认编码与代码文件本身的编码一致。

# coding = utf-8
s = u"中文" # s为unicode
print isinstance(s, unicode) # 用来判断是否为unicode
print s.encode("utf-8", "ignore") # 由unicode转为utf-8,ignore表示忽略非法字符

转载请注明:宁哥的小站 » Python中字符串编码的问题

喜欢 (2)

您必须 登录 才能发表评论!