因此,在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
有人能给我解释一下这里发生了什么事吗?提前谢谢。在
第一次尝试时,您看到的是字符串的编码版本,而不是utf-8格式:
它是用shell使用的任何编码进行编码。在
在第二个示例中,您正在创建一个
unicode
字符串。Python使用shell编码,能够从输入中解码并将其存储为unicode codepoints(\u03b3\u03b5\u03b9\u03ac
)。稍后,当您print
它时,Python也知道shell的编码,并且能够将它从unicode
编码到实际的字节。在关于第三个例子,您显式地使用了^{} 函数。当不使用编码作为参数时,它将使用
ascii
作为默认值。由于ascii
不可能支持希腊字符,Python对此表示不满。在总之,您需要知道您的控制台使用了什么编码,以便确切地知道Python对您的代码做了什么。如果您在Windows上,可以使用
chcp
命令来执行此操作。在Linux上,可以使用locale
命令。在当然我忘了最重要的建议:p
另外值得一提的是,在python3中,这些变化非常显著。在
相关问题 更多 >
编程相关推荐