我在运行Ubuntu10.04LTS,Python2.6.5(r265:790632010年4月16日,13:09:56)
>>> m = 'Šiven'
>>> m
'\xa6iven'
>>> unicode(m)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa6 in position 0: ordinal not in range(128)
我应该如何正确地设置它(编码、解码)以使它准确地写入它所读的内容?在
在Python2.x中,单引号表示一个由字节组成的字符串,而不是字符。您需要一个字符字符串,在2.x中以
u
作为前缀:请注意,只有终端编码与平台编码匹配时,这才有效。你真的应该把两者都设置为UTF-8。在
如果不是这样,则应使用unicode转义符:
^{pr2}$在Python文件(不是终端)中,可以按照PEP 263来设置编码,方法如下:
您可能还希望使用Python3.x,它消除了字节和字符串之间的混淆。在
为了避免这些问题,您可能应该将
# -*- coding: utf-8 -*-
置于utf-8模式,并使用编辑器和其他所有方式,但是如果您想找出哪种编码最适合您当前的输入,您可以尝试这个脚本(将'some string'
替换为更本地化的代码):也就是说,utf-8是你的朋友;使用它。:)
相关问题 更多 >
编程相关推荐