解码/编码字符串,提交'Šiven'但得到'\ xa6烤箱'

时间:2012-03-03 10:42:50

标签: python string encoding decoding

我正在运行Ubuntu 10.04 LTS,Python 2.6.5(r265:79063,2010年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)

我应该如何正确设置它(编码,解码),以便准确写出它的内容?

2 个答案:

答案 0 :(得分:6)

在Python 2.x中,单引号表示 bytes 的字符串,而不是字符。你想要一个字符字符串,它在2.x中以u为前缀:

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

请注意,这仅适用于终端编码与平台编码匹配的情况。你应该把它们都设置为UTF-8。

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

>>> m = u'\u0160iven'
>>> print(m)
Šiven
>>> m.encode('utf-8')
'\xc5\xa0iven'

在Python文件(不是终端)中,您可以通过启动以下文件来设置PEP 263的编码:

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

您可能还想使用Python 3.x,它可以清除字节和字符串之间的混淆。

答案 1 :(得分:0)

您可能应该放置# -*- 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是你的朋友;用它。 :)