基于unicode字符串的Python编码

2024-05-05 03:32:55 发布

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

因此,在python终端中,我键入以下内容:

>>> s = "γειά"       ## it just means 'hi' in Greek
>>> s
'\x9a\x9c\xa0\xe1'   ## What is this? - Is it utf-encoding? Is it ascii escaped?
>>> print s
γειά

现在有趣的是:

^{pr2}$

我对编码非常困惑,尤其是utf-8编码的字符串和/或ascii编码的字符串。以上两个代码段之间的区别是什么?它们是如何绑定unicode函数的?在

>>> result = unicode(s)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x9a in position 0: ordinal
                     not in range(128)

>>> result = unicode(s, 'utf-8')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf8' codec can't decode byte 0x9a in position 0: invalid s
                     tart byte

有人能给我解释一下这里发生了什么事吗?提前谢谢。在


Tags: 字符串inmost编码isasciiunicodeit
1条回答
网友
1楼 · 发布于 2024-05-05 03:32:55

第一次尝试时,您看到的是字符串的编码版本,而不是utf-8格式:

>>> s='\x9a\x9c\xa0\xe1'
>>> s.decode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x9a in position 0: invalid start byte

它是用shell使用的任何编码进行编码。在

在第二个示例中,您正在创建一个unicode字符串。Python使用shell编码,能够从输入中解码并将其存储为unicode codepoints\u03b3\u03b5\u03b9\u03ac)。稍后,当您print它时,Python也知道shell的编码,并且能够将它从unicode编码到实际的字节。在

关于第三个例子,您显式地使用了^{}函数。当不使用编码作为参数时,它将使用ascii作为默认值。由于ascii不可能支持希腊字符,Python对此表示不满。在

总之,您需要知道您的控制台使用了什么编码,以便确切地知道Python对您的代码做了什么。如果您在Windows上,可以使用chcp命令来执行此操作。在Linux上,可以使用locale命令。在

当然我忘了最重要的建议:p

另外值得一提的是,在python3中,这些变化非常显著。在

相关问题 更多 >