HowTo: Convert a Python String to int

In this HowTo i’ll explain how to convert a Python string to int.

What is the Python string to int conversion function?

There might be some times when writing programs that you need to convert a Python string to int. That is to say, you are working with some string data and need it to now be numerical. Perhaps you are reading in data from the user as a string and need to convert this to a number. To do this, you’ll need to use the int() function.

int("123") # Returns 123 as a number

As you can see from the above example, you provide the string you are working with to the int() function and it returns an integer value. As well as converting literal string values, you can also pass a variable to the int() function.

number = "567"
int(number) # Returns 5678 as a number

You need to be aware that using the function on it’s own doesn’t modify the actual variable - it just returns it. In order to save the int number to the variable or another variable the returned value should be assigned to the variable.

number = "890"
number = int(number)

If you do pass a string that has letters or symbols in (other than a minus sign) you will receive a ValueError. So the following is fine:

int("-12")

Whereas these will cause the ValueError exception to be raised:

int("1-2")
int("$100")
int("abc123")

The same thing happens if the string value you pass to the int() function contains a decimal number.

int("12.54") // ValueError

To convert the decimal part of the number in this case, you can use the float() function.

Conclusion

To convert a Python string to int you need to use the int() function. You might want to do this when the user has entered some data from input or raw_input. Just remember to assign the value returned from int() to the variable if you want to save the changed made.