Ste*_*dar 26 python unicode utf-8
什么是unicode字符串?
常规字符串和unicode字符串之间有什么区别?
什么是utf-8?
我正在尝试学习Python,我一直听到这个流行语.下面的代码是做什么的?
i18n字符串(Unicode)
> ustring = u'A unicode \u018e string \xf1'
> ustring
u'A unicode \u018e string \xf1'
## (ustring from above contains a unicode string)
> s = ustring.encode('utf-8')
> s
'A unicode \xc6\x8e string \xc3\xb1' ## bytes of utf-8 encoding
> t = unicode(s, 'utf-8') ## Convert bytes back to a unicode string
> t == ustring ## It's the same as the original, yay!
True
Run Code Online (Sandbox Code Playgroud)
文件Unicode
import codecs
f = codecs.open('foo.txt', 'rU', 'utf-8')
for line in f:
# here line is a *unicode* string
Run Code Online (Sandbox Code Playgroud)
tom*_*tom 45
这个答案是关于Python 2.在Python 3中,str是一个Unicode字符串.
Python的str类型是8位字符的集合.可以使用这些8位字符表示英文字母,但是±,♠,Ω和symbols等符号不能.
Unicode是处理各种字符的标准.每个符号都有一个代码点(一个数字),这些代码点可以使用各种编码进行编码(转换为字节序列).
UTF-8就是这样一种编码.低码点使用单个字节编码,而较高码点编码为字节序列.
Python的unicode类型是代码点的集合.该行ustring = u'A unicode \u018e string \xf1'创建一个包含20个字符的Unicode字符串.
当Python解释器显示值时ustring,它会转义两个字符(Ǝ和ñ),因为它们不在标准的可打印范围内.
该行s = unistring.encode('utf-8')使用UTF-8对Unicode字符串进行编码.这会将每个代码点转换为适当的字节或字节序列.结果是一个字节集合,作为一个返回str.大小s为22个字节,因为其中两个字符具有高代码点,并且被编码为两个字节的序列而不是单个字节.
当Python解释显示的值s,它逸出不在可打印范围(四个字节\xc6,\x8e,\xc3,和\xb1).这两对字节不像之前那样被视为单个字符,因为s它是类型的str,而不是unicode.
这条线t = unicode(s, 'utf-8')与之相反encode().它通过查看s字节序列的字节和解析字节序列来重建原始代码点.结果是Unicode字符串.
调用codecs.open()指定utf-8为编码,它告诉Python将文件内容(字节集合)解释为使用UTF-8编码的Unicode字符串.
| 归档时间: |
|
| 查看次数: |
60326 次 |
| 最近记录: |