在 Python 中比较字符串和数字

发布于 2024-12-24 20:56:49 字数 133 浏览 0 评论 0原文

为什么下面的片段会表现得像它的行为?

>>> '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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

飘然心甜 2024-12-31 20:56:49

来自文档

CPython实现细节:除数字之外的不同类型的对象按其类型名称排序;不支持正确比较的相同类型的对象按其地址排序。

所以这只是 CPython 中发生的事情 ('int' < 'str'),但不保证在其他实现中发生。

事实上,这个行为在python3中已经被删除了:

>>> '10' > 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
>>> 100 < '10'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()

From the documentation:

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

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:

>>> '10' > 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
>>> 100 < '10'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
怕倦 2024-12-31 20:56:49

来自 manual

CPython implementation detail: Objects of different types except numbers are 
ordered  by their type names; objects of the same types that don’t 
support proper comparison are ordered by their address.

因此,如果您比较这两种类型: int / string 你有一个按元素类型的字典顺序

From manual:

CPython implementation detail: Objects of different types except numbers are 
ordered  by their type names; objects of the same types that don’t 
support proper comparison are ordered by their address.

So if you compare this two types: int / string you have a lexicographic order bye the type of elements

握住我的手 2024-12-31 20:56:49

不同的运算符被调用,在某个时刻 int 的 __gt__,在另一个时刻,str 的 __lt__

检查这一点:

class t(int):
  def __gt__(self, other):
    print 'here', v
    return v

class t2(str):
  def __lt__(self, other):
    v = super(t2, self).__lt__(other)
    print 'ohere', v
    return v

if __name__ == '__main__':
  a = t('10')
  b = t2(100)

  a > b
  b < a

different operators are getting called, at one point int's __gt__, at another, str's __lt__

check this:

class t(int):
  def __gt__(self, other):
    print 'here', v
    return v

class t2(str):
  def __lt__(self, other):
    v = super(t2, self).__lt__(other)
    print 'ohere', v
    return v

if __name__ == '__main__':
  a = t('10')
  b = t2(100)

  a > b
  b < a
巾帼英雄 2024-12-31 20:56:49

由于 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 do printf("I've got %i bananas", 5000);

Check out Python docs chapter 5: Built-in Types

蓝眼睛不忧郁 2024-12-31 20:56:49

我不是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文