如何比较字符串和整数在python? [英] How to compare string and integer in python?
问题描述
我有这个简单的python程序。我运行它,它打印是
,实际上我希望它不打印任何东西,因为 14
不大于 14
。
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
.
我看到了这个相关问题,但它不是很有帮助。
I saw this related question, but it isn't very helpful.
#! /usr/bin/python
import sys
hours = "14"
if (hours > 14):
print "yes"
我做错了什么?
推荐答案
将字符串转换为整数 int
:
hours = int("14")
if (hours > 14):
print "yes"
在CPython2中,当比较两个不同类型的非数值对象时,比较是通过比较类型。由于'int'< 'string'
,任何int小于任何字符串
In CPython2, when comparing two non-numerical objects of different types, the comparison is performed by comparing the names of the types. Since 'int' < 'string'
, any int is less than any string.
In [79]: "14" > 14
Out[79]: True
In [80]: 14 > 14
Out[80]: False
这是一个经典的Python陷阱。在Python3中,这个疣已被更正 - 比较不同类型的非数值对象默认会引起TypeError。
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.
As 展示在文档中:
CPython实现细节:不同类型的对象(
除外)按照类型名称排序;对不支持正确比较的相同类型
的对象按其地址排序。
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.
这篇关于如何比较字符串和整数在python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!