在 Python 中比较字符串和数字
为什么下面的片段会表现得像它的行为?
>>> '10' > 100
True
>>> 100 < '10'
True
难道不应该引发异常吗?
Why does the following piece behave like it behaves?
>>> '10' > 100
True
>>> 100 < '10'
True
Shouldn't it raise an exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来自文档:
所以这只是 CPython 中发生的事情 (
'int' < 'str'
),但不保证在其他实现中发生。事实上,这个行为在python3中已经被删除了:
From the documentation:
So it's just something that happens in CPython (
'int' < 'str'
), but that isn't guaranteed to happen in other implementations.In fact, this behaviour has been removed in python3:
来自 manual:
因此,如果您比较这两种类型:
int / string
你有一个按元素类型的字典顺序From manual:
So if you compare this two types:
int / string
you have a lexicographic order bye the type of elements不同的运算符被调用,在某个时刻 int 的 __gt__,在另一个时刻,str 的
__lt__
检查这一点:
different operators are getting called, at one point int's
__gt__
, at another, str's__lt__
check this:
由于 Python 实现了数字的隐式类型转换,因此它们可以作为字符串打印,而无需进行显式转换。
在与字符串
"10"
进行比较时,Python 将1000
转换为字符串"1000"
。根据Python解释器,“1000”
确实比“10”大。这就是为什么:
"Ive got %s Bananas" % 5000
有效,并且与 C 或其他没有隐式类型转换的语言不同,我不必执行printf("I 've got %ibananas", 5000);
查看 Python 文档第 5 章:内置类型
Because Python implements implicit type conversions for numbers so they may be printed as strings without doing an explicit conversion.
Python is converting
1000
into the string"1000"
when doing the comparison to the string"10"
. And according to the Python intepreter,"1000"
is indeed larger than "10".This is why:
"I've got %s bananas" % 5000
works, and unlike in C or another language without implicit type conversion, I didn't have to doprintf("I've got %i bananas", 5000);
Check out Python docs chapter 5: Built-in Types
我不是 100% 确定,但这里可能会发生一些内部类型转换。它可能正在执行所谓的字典比较,其中“1”(ASCII 中的 49)大于 1(第一个数字),依此类推。
I am not 100% sure, but some internal type conversion might be happening here. It might be doing what is called lexicographic comparison, where '1' which is 49 in ASCII is greater than 1 (the first digit), and so on.