How To Compare String and Integer in Python

In this tutorial, you will learn to compare string and integer in Python.

In Python, if you want to compare a String with an Integer then all you are required to make sure is that the string variable is first typecasted to the integer.

Also, you have to make sure that the string is containing only numbers and no other alphabets are part of the string variable.

Using Typecasting To Compare String and Integer

Let us see in the below code how you can use the typecasting method to compare string and integer in Python.

#Initializing the String Variable
stringNum = "123"

#using Typecasting to Compare the String 
#To integer
if int(stringNum) <= 123:
    print("Typecasted Number is compared.")
else:
    print("Not Working.")

Output:

Typecasted Number is compared.

As you can see in the above code, I have typecasted the stringNum variable to integer and then compared it to the integer values to 123. And you can see using this method you can easily compare a string and number in Python.

How To Compare String and Integer in Python

Wrap Up

I hope you understood about the typecasting and how it works in case of comparing the string and number in Python.

Let me know in the comment section if you think you know a better method than the one discussed above. I will be happy to add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. How To Print Fractional Part In Python
  2. [Fix] SyntaxError: unexpected EOF while parsing in Python
  3. Convert All Strings in a List to Int in Python
  4. Working With The Current Directory In Python

Leave a Comment