Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare string and integer in python?

Tags:

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?

like image 761
CodeBlue Avatar asked Jul 15 '13 19:07

CodeBlue


People also ask

How do you compare strings to integers in Python?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.

Can we compare string and integer?

If you want to compare their string values, then you should convert the integer to string before comparing (i.e. using String. valueOf() method). If you compare as integer values, then 5 is less than "123". If you compare as string values, then 5 is greater than "123".

How do you compare strings and numbers?

You can convert a numeric string into integer using Integer. parseInt(String) method, which returns an int type. And then comparison is same as 4 == 4 .

Can I use == to compare strings in Python?

Python comparison operators can be used to compare strings in Python. These operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).


Video Answer


2 Answers

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.

like image 85
unutbu Avatar answered Sep 18 '22 02:09

unutbu


I think the best way is to convert hours to an integer, by using int(hours) .

hours = "14"  if int(hours) > 14:     print("yes")``` 
like image 24
OakenDuck Avatar answered Sep 21 '22 02:09

OakenDuck