Avoiding the error of comparing number and string

We all made this mistake in python:

if ( number < string ):

      

python silently accepts this and just gives the wrong output.

Thank goodness python 3 is finally warning us. But in some cases python 2.7 is required. Is there any way in python 2.7 to guard against this error other than "just be careful" (which we all know doesn't work 100% of the time)?

+3


source to share


4 answers


You can explicitly convert both numbers to int

. The string will be converted and the number will not be executed (this is already an int). Thus, it saves you the trouble of remembering what a number matters:

a = 11
b = "2"
print a > b # prints False, which isn't what you intended
print int(a) > int(b) # prints True

      



EDIT:
As noted in the comments, you cannot assume the number is an integer. However, using the same set, albeit with the proper function - float

should work fine:

a = 11
b = "2"
print a > b # prints False, which isn't what you intended
print float(a) > float(b) # prints True

      

+3


source


If you really want to be 100% sure that comparing strings and int is not possible, you can overload the method __builtin__.int

( __builtin__.float

and so on as needed) to disallow comparing ints (and float, etc). ) with strings. It will look like this:

import __builtin__

class no_str_cmp_int(int):
    def __lt__(self,other):
        if type(other) is str:
            raise TypeError
        return super.__lt__(other)
    def __gt__(self,other):
        if type(other) is str:
            raise TypeError
        return super.__gt__(other)
    # implement __gte__, __lte__ and others as necessary

# replace the builtin int method to disallow string comparisons
__builtin__.int = no_str_cmp_int

x = int(10)

      

Then if you try to do something like this, you get this error:

>>> print x < '15'

Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    print x < '15'
  File "tmp.py", line 7, in __lt__
    raise TypeError
TypeError

      



However, there is a big caveat to this approach. It only replaces the function int

, so every time you create an int you need to pass it through the function as you did in the declaration x

above. The literals will still be the original type int

and as far as I know there is no way to change this. However, if you create these objects correctly, they will continue to work with the 100% assurance you desire.
0


source


Just convert your string or any datatype to float first. When the two data types are the same, then we can compare them.

Suppose

a = "10"
b= 9.3
c=9

      

We want to add a, b, c .. So,

So, the correct way to add these three is to convert them to the same data type and then add.

a = float(a)
b = float(b)
c = float(c)

print a+b+c

      

0


source


You can check if each variable is such an int:

if ( isinstance(number, int) and isinstance(string, int) ):
   if (number < string):
      Do something
   else:
      Do something else
else :
   print "NaN"

      

* Edit: There should also be code to test the float:

if ( isinstance(number, (int,float )) and isinstance(string, (int,float) ) ):

      

-1


source







All Articles