发布时间:2019-09-08 09:10:20编辑:auto阅读(1978)
关于python编码的基本常识
unicode类型 “密文”是其他的编码格式 如gbk utf-8 latin-1等等.encode([目标编码格式]) 对象必须为unicode类型.decode([源编码格式]) 对象为str类型\x67\x4e \u674e񧓠x674E0x0000674E\xe6\x9d\x8e \xe6\x9d\x8e%E6%9D%8E\346\235\216\xc0\xee gb2312 gbk gb18030 \xc0\xee设置.py文件的编码格式
SyntaxError: Non-ASCII character '\xe6' in file... , but no encoding declared;
sys.getdefaultencoding()亦可得知
>>> sys.getdefaultencoding()
'ascii'
设置方式 在.py文件首部 加上代码
#coding=<encoding>
<encoding><encoding>为utf-8字符串文字量的类型
前面加u 为’unicode’类型
>>> str_u = u"中文"
>>> type(str_u)
<type 'unicode'>前面不加u 为’str’类型
>>> str = str_u.encode('gbk')
>>> type(str)
<type 'str'>
>>> str1 = "中文"
>>> type(str1)
<type 'str'>关于print输出中文字符串
unicode类型 编码为’gbk’均可正常显示文字
>>> str = "中文"
>>> print str
中文
>>> str_u = u"中文"
>>> print str_u
中文编码为’ascii’ 则会出现UnicodeEncodeError错误
>>> print str_u.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)编码为’utf-8’ 则会乱码显示
>>> print str_u.encode('utf-8')
涓枃Windows的文件/文件夹的中文名字
.encode('gbk')Windows读写文件内容
utf-8 这样Sublime Text打开后不需要ConvertToUTF8爬虫结果的存储
NavigableStringNavigableString底层类型为unicode.replace()方法后可转换为unicode类型日语假名和日语汉字
其他
上一篇: python的markdown扩展开发
下一篇: 用struct模块实现python so
51180
50588
41213
38036
32500
29403
28265
23119
23084
21411
1464°
2181°
1806°
1733°
2043°
1798°
2479°
4169°
4034°
2880°