解码/编码字符串,提交'Šiven'但获取'\ xa6iven'

Kri*_*ian 0 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)
Run Code Online (Sandbox Code Playgroud)

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

phi*_*hag 6

在Python 2.x中,单引号表示字节串,而不是字符.你想要一个字符的字符串,其前缀u在2.X:

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

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

如果不是这种情况,您应该使用unicode转义:

>>> m = u'\u0160iven'
>>> print(m)
Šiven
>>> m.encode('utf-8')
'\xc5\xa0iven'
Run Code Online (Sandbox Code Playgroud)

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

# -*- coding: utf-8 -*-
Run Code Online (Sandbox Code Playgroud)

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