咨询热线:4006-75-4006

售前:9:00-23:30    备案:9:00-18:00    技术:7*24h

python3编码调整

2018-03-14 11:50:19 14440次

python2默认的编码是ascii,python没办法处理非ascii编码的,此时需要自己设置将python的默认编码,一般设置为utf8的编码格式。

import sys  
reload(sys)  
sys.setdefaultencoding('utf8')

这样,转换之后默认编码就改为utf8了。


Python3.x中已经修改了编码的方式,明确了str和byte的区分,不需要使用这个转换了。

Python3.x中sys没有setdefaultencoding了,因为不需要。

注:python3 默认的编码为unicode

UTF-8(8-bit Unicode Transformation Format)是一种针对Unicode的可变长度字符编码,又称万国码。UTF-8用1到6个字节编码Unicode字符。

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

bytes.decode(encoding="utf-8", errors="strict")

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

str.encode(encoding='UTF-8',errors='strict')


首页
最新活动
个人中心