How to compare string and integer in python?

六眼飞鱼酱① 提交于 2019-12-17 04:34: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"

What am I doing wrong?


回答1:


Convert the string to an integer with 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 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

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 explained in the docs:

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.



来源:https://stackoverflow.com/questions/17661829/how-to-compare-string-and-integer-in-python

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