如何在python中比较字符串和整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17661829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare string and integer in python?
提问by CodeBlue
I have this simple python program. I ran it and it prints yes
, when in fact I expect it to not print anything because 14
is not greater than 14
.
我有这个简单的 python 程序。我运行它并打印yes
,实际上我希望它不会打印任何内容,因为14
它不大于14
.
I saw this relatedquestion, but it isn't very helpful.
我看到了这个相关的问题,但这不是很有帮助。
#! /usr/bin/python
import sys
hours = "14"
if (hours > 14):
print "yes"
What am I doing wrong?
我究竟做错了什么?
采纳答案by unutbu
Convert the string to an integer with int
:
将字符串转换为整数int
:
hours = int("14")
if (hours > 14):
print "yes"
In CPython2, when comparing two non-numerical objects of different types, the comparison is performed by comparing the namesof the types. Since 'int' < 'string'
, any int is less than any string.
在 CPython2 中,当比较两个不同类型的非数值对象时,比较是通过比较类型的名称来进行的。因为'int' < 'string'
,任何 int 都小于任何 string。
In [79]: "14" > 14
Out[79]: True
In [80]: 14 > 14
Out[80]: False
This is a classic Python pitfall. In Python3 this wart has been corrected -- comparing non-numerical objects of different type raises a TypeError by default.
这是一个典型的 Python 陷阱。在 Python3 中,这个问题已经得到纠正——默认情况下,比较不同类型的非数字对象会引发 TypeError。
如文档中所述:
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.
CPython实现细节:除数字外的不同类型的对象按类型名称排序;不支持正确比较的相同类型的对象按其地址排序。
回答by OakenDuck
I think the best way is to convert hours
to an integer, by using int(hours)
.
我认为最好的方法是hours
使用int(hours)
.
hours = "14"
if int(hours) > 14:
print("yes")```