In previous article, we covered Comparison operators in Python. That works only when we compare similar data types i.e. a string with a string or an integer value with an integer. But, what if we need to compare a string with an integer? Even if we could, it would lead to some random outcome. We can't do that directly but there is way around for certain inputs.
First start with what happens when we compare an integer with string -
x = 10 y = "21" if (x<y): print("10<21 and it worked!!")
At this stage, it would throw an error -
TypeError: '<' not supported between instances of 'int' and 'str'
Clearly, it couldn't compare and threw a TypeError along-with the reason. The less than operator(<) is not supported for int and str values.
The value stored in variable y, looks like an integer value. But, in reality its a string. We can verify it with type() -
It returns with -
And, for variable y -
Compare string with integer in Python
So, how do we compare such variables? We can convert the string value to an integer or even float. It can be done through int() and float() methods. We continue with the above example but, this time around with a difference. We either use int() or float() method -
x = 10 y = "21" if (x<int(y)): print("10<21 and it worked!!")or,
x = 10 y = "21" if (x<float(y)): print("10<21 and it worked!!")
For both the cases, it would return with -
10<21 and It worked!!
In conclusion, we have covered how to compare string with integer in Python here. Though not applicable to all the combinations as we can't compare "abc" with 23. These are entirely different data types which can't be utilized this way. For instance,
It would throw a ValueError -
ValueError: invalid literal for int() with base 10: 'abc'
But, for combinations mentioned in this article - we can do that.