对字符串进行解码/编码,提交“shiven”,但获取“\xa6iven”

2024-10-01 00:16:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在运行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)

我应该如何正确地设置它(编码、解码)以使它准确地写入它所读的内容?在


Tags: inmoststdinlineunicodecallfilelast
2条回答

在Python2.x中,单引号表示一个由字节组成的字符串,而不是字符。您需要一个字符字符串,在2.x中以u作为前缀:

>>> m = u'Šiven'
>>> print(m)
Šiven
>>> m.encode('utf-8') # Get the corresponding UTF-8 bytestring
'\xc5\xa0iven'

请注意,只有终端编码与平台编码匹配时,这才有效。你真的应该把两者都设置为UTF-8。在

如果不是这样,则应使用unicode转义符:

^{pr2}$

在Python文件(不是终端)中,可以按照PEP 263来设置编码,方法如下:

# -*- coding: utf-8 -*-

您可能还希望使用Python3.x,它消除了字节和字符串之间的混淆。在

为了避免这些问题,您可能应该将# -*- coding: utf-8 -*-置于utf-8模式,并使用编辑器和其他所有方式,但是如果您想找出哪种编码最适合您当前的输入,您可以尝试这个脚本(将'some string'替换为更本地化的代码):

encodings = ['ascii', 'cp037', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig']

def test(s):
    for enc in encodings:
        try:
            u = unicode(s, enc)
            print u, enc
        except: pass

test('some string')

也就是说,utf-8是你的朋友;使用它。:)

相关问题 更多 >