Skip to content Skip to sidebar Skip to footer

Turn A Variable From String To Integer In Python

I'm having a problem with the int() function. I tried to use it in a simple program, but remains not working. This is my short program. I use int() to turn the a variable from a st

Solution 1:

int(a) doesn't mutate a, it creates a new object and returns it. Try this:

a = '4'
i = int(a)
if i > 2:
    print("It's working")

Notice that the new variable I created on line 2 has a different name from the one I created on line 1. It doesn't have to. In fact, sometimes it can be more readable to re-use the name:

a = '4'     # Now `a` is a `str`
a = int(a)  # Now `a` is an `int`if a > 2:
    print("It's working")

Solution 2:

# or mutate the a by redefining a:
a = '4'
a = int(a)
if a > 2:
    print("It's working")

Solution 3:

Instead of type casting it before the for loop, you can keep "a" as a str and just type cast it to int in the for loop. This will preserve your str dataype while you will get your desired output.

a = '4'ifint(a) > 2:
    print( "It's working" )

In your program. you are converting str to int only for that instance. You're not storing it anywhere. So your variable a points to the str which is stored before type casting it.

Post a Comment for "Turn A Variable From String To Integer In Python"