Skip to main content
 首页 » 编程设计

python之为什么 unicode 字符串不能与 python 中的字节字符串进行比较

2025年05月04日33EasonJim

在 Pattern python 文档中,我看到“Unicode String can't be compared with Byte String”,但为什么呢? 您可以在此处阅读该行:https://github.com/python/cpython/blob/3.5/Lib/re.py

请您参考如下方法:

Python 3 引入了一个颇具争议的更改,其中所有 Python 字符串都是 Unicode 字符串,并且所有字节字符串都需要指定编码才能转换为 Unicode 字符串。

这符合 Python 的“显式优于隐式”原则,并消除了大量潜在的错误,在这些错误中,隐式转换会在程序员粗心或没有意识到其含义时悄悄地产生错误或损坏的结果。

不利的一面是,除非您正确理解模型,否则很难编写混合 Unicode 和字节字符串的代码。 (好吧,以前也很困难;但是那些健忘的程序员仍然如此,并认为他们的代码可以正常工作,直到有人对其进行了正确的测试。现在他们会提前发现错误。)

简要地引用自the Stack Overflow character-encoding tag info page :

just like changing the font from Arial to Wingdings changes what your text looks like, changing encodings affects the interpretation of a sequence of bytes. For example, depending on the encoding, the bytes 0xE2 0x89 0xA0 could represent the text ≠in Windows code page 1252, or Б┴═ in KOI8-R, or the character ≠ in UTF-8.

Python 2 会在幕后做一些不明显的事情来将这个字节字符串强制转换为本地字符串,这取决于上下文可能涉及本地系统的“默认编码”,从而在不同的系统上产生不同的结果,创建一些非常困难的错误。如果要将字节转换为字符串,Python 3 要求您明确说明应如何解释这些字节。

bytestr = b'\xE2\x89\xA0'  
fugly = bytestr.decode('cp1252')  # u'≠' 
cyril = bytestr.decode('koi8-r')  # u'Б┴═'  
wtf_8 = bytestr.decode('utf-8')   # u'≠'