python2和python3的编码格式

it2022-05-05  159

1、Python2和Python3的 字符编码 和 字符类型

Python3: Unicode字符串 str 类型 非Unicode字符串 bytes 类型

Python2: Unicode字符串 unicode 类型 非Unicode字符串 str 类型

2、python的Unicode和非Unicode的转换

非Unicode字符串,可以通过decode解码为Unicode字符串 unicode_str = utf8_str.decode(“utf-8”) # Unicode字符串, 可以通过 encode 编码为其他编码 gbk_str = unicode_str.encode(“gbk”)  

3、终端创建字符串的编码 在解释器终端创建的字符串 Python2:根据操作系统决定 Linux为utf-8、简体简体中文Windows 为 gbk。注意,如果是iPython创建的,都是 utf-8 Python3:Unicode 编码

4、文件编码 写入字符串到文件中,文件创建成功,则文件编码等同于写入的字符串编码。

如果写入了其他编码的字符串,则文件编码被修改,原来的内容会变成"乱码"。

5、处理字符串写入文件时候的编码。

Python不能直接写 Unicode字符串到文件中,必须写入 非Unicode

1. 手动转码处理     Python3:         # w 必须写 Unicode, wb 写非Unicode(gbk、utf-8、jpg、mp4)         with open("xxx.txt", "wb") as f:             f.write(unicode_str.encode("utf-8"))     Python2:         # w 写字符串, wb 写非字符串         with open("xxx.txt", "w") as f:             f.write(unicode_str.encode("utf-8")) 2. 通过 open()方法的 encoding 参数     Python3:         with open("xxx.txt", "w", encoding="utf-8") as f:             f.write(unicode_str)     Python2:         Python2的 open() 没有 encoding,但是可以通过 codecs 模块解决         import codecs         with codecs.open("xxx.txt", "w", encoding="utf-8") as f:             f.write(unicode_str) 3. 如果强行写入Unicode字符串,且并没有通过 1 和 2 处理,则Python解释器编码尝试转码再写入。      with open("xxx.txt", "w") as f:          f.write(unicode_str)     Python2 默认解释器编码是 ascii,在处理中文则报错 UnicodeEncodeError 无法按 ASCII编码处理中文字符串,         解决方案,将Python2 解释器编码修改为 utf-8         import sys         reload(sys)         sys.setdefaultencoding("utf-8")     Python3 默认解释器编码是平台的编码格式,一定需要设置 !

 

更多内容请关注微信公众号“外里科技”

 


最新回复(0)