Compare string to float in Python [duplicate]

不羁的心 提交于 2020-01-03 03:48:26

问题


I tried this in python shell

>>> a='apple'
>>> b=11.1
>>> a>b
True
>>> a
'apple'
>>> b>a
False

Can someone explain to me how a>b is True? When a is an string and b is float.


回答1:


Order comparison between elements of different types was a "design bug" in Python 2.x that has been removed in Python 3 (where you get a runtime error).

Correcting it wasn't an option before 3.x because of a lot of existing software that does sorting on heterogeneous containers (and version 3 is the first in which backward compatibility is intentionally broken).

In Python 2.x you can compare anything for </>, with the only exception of complex numbers where this is explicitly forbidden.

The ordering result of comparison of different types is arbitrary but fixed at least for a given run of the Python interpreter, see http://docs.python.org/2/reference/expressions.html#not-in . Values of different non-numeric types are always considered different.




回答2:


In Python 2, comparison between incomparable types often "works", giving meaningless results. Sometimes it's fun: 'aleph0' > float('+inf'). But most of the time it's just silly.

So Python 3 has removed this, and 'a' > 1.0 quite reasonably raises a TypeError under it.



来源:https://stackoverflow.com/questions/19713498/compare-string-to-float-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!