为什么在 Python3 中将字节与 str 的比较失败 [英] Why does comparison of bytes with str fails in Python3

查看:41
本文介绍了为什么在 Python3 中将字节与 str 的比较失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python3 中,此表达式的计算结果为 False:

In Python3 this expression evaluates as False:

b"" == ""

而在 Python2 中这个比较是 True:

while in Python2 this comparison is True:

u"" == ""

使用 is 检查身份显然在这两种情况下都失败了.

Checking for identity with is obviously fails in both cases.

但为什么他们会在 Python3 中实现这样的行为?

But why would they implement such a behaviour in Python3?

推荐答案

在 Python 2.x 中,unicode 的设计目标是实现 unicode 和 unicode 之间的透明操作.通过在 2 种类型之间隐式转换来转换字节字符串.当你做比较u"" == ""时,unicode LHS会先自动编码成字节串,然后再和str比较代码> RHS.这就是它返回 True 的原因.

In Python 2.x, the design goal for unicode is to enable transparent operations between unicode & byte strings by implicitly converting between the 2 types. When you do the comparison u"" == "", the unicode LHS is automatically encoded into a byte string first, and then compared to the str RHS. That's why it returned True.

相比之下,Python 3.x 从 Python 2 中混乱的 unicode 中吸取了教训,决定明确有关 unicode 与字节字符串的所有内容.因此,b"" == ""False 因为字节字符串不再自动转换为 unicode 进行比较.

In contrast, Python 3.x, having learned from the mess of unicode that was in Python 2, decided to make everything about unicode vs. byte strings explicit. Thus, b"" == "" is False because the byte string is no longer automatically converted to unicode for comparison.

这篇关于为什么在 Python3 中将字节与 str 的比较失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆