How to Compare String and Integer in Python

How to compare string and integer in python?

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.

Compare string and integer in same if statement

input() will always return a string unless you explicity convert it. So using ask_option = int(input("Your option: ")) will already satisfy checking if ask_option is an integer as an exception will be raised otherwise.

As for evaluating the integer, you can accomplish this in a single line such as:

if not 1 <= ask_option <= 4:
print("Not a valid option")

How can Python compare strings with integers?

Python is not C. Unlike C, Python supports equality testing between arbitrary types.

There is no 'how' here, strings don't support equality testing to integers, integers don't support equality testing to strings. So Python falls back to the default identity test behaviour, but the objects are not the same object, so the result is False.

See the Value comparisons section of the reference documentation:

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

If you wanted to compare integers to strings containing digits, then you need to convert the string to an integer or the integer so a string, then compare.

How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?

From the python 2 manual:

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.

When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers).

When you order a numeric and a non-numeric type, the numeric type comes first.

>>> 5 < 'foo'
True
>>> 5 < (1, 2)
True
>>> 5 < {}
True
>>> 5 < [1, 2]
True

When you order two incompatible types where neither is numeric, they are ordered by the alphabetical order of their typenames:

>>> [1, 2] > 'foo'   # 'list' < 'str' 
False
>>> (1, 2) > 'foo' # 'tuple' > 'str'
True

>>> class Foo(object): pass
>>> class Bar(object): pass
>>> Bar() < Foo()
True

One exception is old-style classes that always come before new-style classes.

>>> class Foo: pass           # old-style
>>> class Bar(object): pass # new-style
>>> Bar() < Foo()
False

Is this behavior mandated by the language spec, or is it up to implementors?

There is no language specification. The language reference says:

Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

So it is an implementation detail.

Are there differences between any of the major Python implementations?

I can't answer this one because I have only used the official CPython implementation, but there are other implementations of Python such as PyPy.

Are there differences between versions of the Python language?

In Python 3.x the behaviour has been changed so that attempting to order an integer and a string will raise an error:

>>> '10' > 5
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'10' > 5
TypeError: unorderable types: str() > int()

how do I compare a string of integers with an integer?

Your problem is comparing an integer d to a string as you iterate over str_of_ints. Your data types must match. 4 is not the same as '4'. This can be solved by converting your searched value to a str using the str() method:

d = 4
int_list = [1,2,3,4,5]
string_digits = [str(int) for int in int_list]
str_of_ints = ''.join(string_digits)

# this produces -> str_of_ints = 1491625 (and this is a string)

if str(d) in str_of_ints:
print('hello')

python numeric string comparison

When comparing strings they're compared by the ascii value of the characters. '1' has a value 49, and '4' is 52. So '1' is < '4'. '9' however is 57, so '9' is > '4'.

If you want to compare them numerically you could just int() the strings first like:

print int('100') < int('45')


Related Topics



Leave a reply



Submit