发布时间:2019-09-08 09:10:20编辑:auto阅读(1765)
关于python编码的基本常识
unicode
类型 “密文”是其他的编码格式 如gbk
utf-8
latin-1
等等.encode([目标编码格式])
对象必须为unicode
类型.decode([源编码格式])
对象为str
类型\x67\x4e
\u674e
李
0x674E
0x0000674E
\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
爬虫结果的存储
NavigableString
NavigableString
底层类型为unicode
.replace()
方法后可转换为unicode
类型日语假名和日语汉字
其他
上一篇: python的markdown扩展开发
下一篇: 用struct模块实现python so
48805
47853
38628
35805
30233
26977
26020
20848
20636
19011
426°
502°
532°
541°
524°
508°
576°
641°
760°
810°