How to Convert Python String to Int: Complete Tutorial
The process of converting a string to an integer in python is simple, just use the int() function, such as x = int(x) to convert the variable x from a string to an integer as seen here:
x = "3"
x = int(x)
print(x)
print("The string x is now a ", type(x))
3
The string x is now a <class ‘int’>
The remainder of this article goes into great detail about converting a string into an integer and related matters.
We start with the question of what is a string and what is ‘int’? Int is used in python to represent an integer which, like string, is a data type.
To hold different types of data we use data types.
For example, we have numbers that we may with to use with some calculations, we have numbers used in dates and times, and also numbers used in normal text such as telephone numbers.
Data Types
Numbers include integer and floating point numbers:
- Integers (int): Whole numbers without any decimal point, like 5, -3, 1000, etc.
- Floating-point numbers (float): Numbers that have a decimal point or use exponential (scientific) notation, like 3.14, -0.001, 1.45×103, etc.
Text written in sentences such as words are called strings and are created with the use of quotation marks in python:
- Strings (str): Sequences of characters enclosed within either single quotes (‘) or double quotes (“). For example, “hello”, ‘world’, “123”, etc.
These are called the primitive types in python.
There are other data types like a Boolean (True or False), and when there is more than one value we can use data structures such as lists, sets, tuples and dictionaries.
2 -Python Casting and Data Type Conversion
Converting a data type into a different data type is known as casting, data casting or data type conversion in python. Lets explain out first example
x = "3"
x = int(x)
print(x)
print("The string x is now a ", type(x))
3
The string x is now a <class ‘int’>
- A string variable called x with a value of ‘3’ is created first.
- This string is then converted into an integer with a value of 3
- The value of x is printed
- The type of x is also printed t show that it is a string.
- The output shows that, in python, the integer data type is a class, and that class is known as ‘int’
Using the int() Function
If we have a digit that we want to use like a number then we need to make sure it is of the integer data type. If we have a string then the results will not be what we expect.
Let’s see a simple example of the difference when multiplying an age of 21, first incorrectly as a string , then correctly as an integer.
There is no error message, but have a look at the output.
age = "21"
print (age*2)
age = int(age)
print(age*2)
2121
42
We expect to see the value of 42 for the variable age, which we do when we convert the string into an integer. But what is 2121?
Using the symbol * does multiply integers as you expect, but it also repeats strings the given amount of times. So the two characters of ‘2’ the ‘1’ are repeated to create the new sting of ‘2121’.
3 - Examples of String to Int Conversion
Here are some examples of string to int conversion.
age = "19"
days = '14'
temp = '-5'
cost = "1000"
age = int(age)
days = int(days)
temp = int(temp)
cost = int(cost)
print(age,days,temp,cost)
Output: 19 14 -5 1000
4 - Convert String to Int in Python Safely
There are different formats of numbers that can result in an error message when a python string convert to an integer is attempted. The suggested approach to deal with issues is to use try and except.
The following code snippets show the tests and results of different forms of the integer 3. In the following strings there are some potential issues that are tested below:
3.0 , 3.2 , -3 , 003
test = "3.0"
test = int(test)
print(test)
print("The string x is now a ", type(test))
Output: ValueError: invalid literal for int() with base 10: ‘3.0’
test = "3.2"
test = int(test)
print(test)
print("The string x is now a ", type(test))
Output: ValueError: invalid literal for int() with base 10: ‘3.2’
test = "-3"
test = int(test)
print(test)
print("The string x is now a ", type(test))
The string x is now a <class ‘int’>
test = "003"
test = int(test)
print(test)
print("The string x is now a ", type(test))
Output: 3
The string x is now a <class ‘int’>
Try and Except
We can see the floats 3.0 and 3.2 are problematic. If we know the string is a number but we don’t know if it is a floating point number or an integer we can do the following:
#solution for a float format
test = '3.0'
try:
test = int(float(test))
except:
test = -1
print(test)
print("The string x is now a ", type(test))
Output: 3
The string x is now a <class ‘int’>
Do you wish to round down numbers? If you do then this code will work as testing with 3.2 resulted in the number being changed to 3 to be an integer.
#solution for a float format
test = '3.2'
try:
test = int(float(test))
except:
test = -1
print(test)
print("The string x is now a ", type(test))
Output: 3
The string x is now a <class ‘int’>
5 - Alternative Approaches to Convert a String to an Integer
There are other approaches with different success rates with our testing (3, 3.0, 3.2, -3, 003). The code will show how a successful convert from string to int can be seen, but we will also put the output for all of the testing.
isdigit()
test = "3"
if test.isdigit():
test = int(test)
print(test)
print("The string x is now a ", type(test))
else:
print(test, "is not a valid integer")
Output: 3
The string x is now a <class ‘int’>
Testing the strings 3.0, 3.2, -3 and ‘003’.
Output: 3.0 is not a valid integer
Output: 3.2 is not a valid integer
Output: -3 is not a valid integer
Output: 3
The string x is now a <class ‘int’>
The last example tests the string “003” and does convert correctly. Both floats are correctly identified as not integers and can be dealt with in the else or except options in the code. The major error is with -3, as the results state this is not a valid integer.
isnumeric()
test = "3"
if test.isnumeric():
test = int(test)
print(test)
print("The string x is now a ", type(test))
else:
print(test, "is not a valid integer")
Output: 3
The string x is now a <class ‘int’>
Testing the strings 3.0, 3.2, -3 and ‘003’.
Output: 3.0 is not a valid integer
Output: 3.2 is not a valid integer
Output: -3 is not a valid integer
Output: 3
The string x is now a <class ‘int’>
The results for isnumeric() and isdigit() are identical.
isinstance()
test = "3"
if isinstance(test,int):
test = int(test)
print(test)
print("The string x is now a ", type(test))
else:
print(test, "is not a valid integer")
Output: 3 is not a valid integer
The data type needs to be an integer for isinstance() to return True, so it is not relevant for our purposes.
eval()
test = "3"
print(eval(test)+0)
print("The string x is now a ", type(test))
Output: 3
The string x is now a <class ‘str’>
The data type has not changed from string to int using eval although we were able to apply calculations of the digit as if it was an integer.
test = "3.2"
print(eval(test)+1)
print("The string x is now a ", type(test))
Output: 4.2
The string x is now a <class ‘str’>
In this example to number 3.2 is not an integer but we can add one to it as if it was a floating point number, giving the output of 4.2 (3.2 + 1), yet we still have a string data type.
test = "003"
print(eval(test)+1)
print("The string x is now a ", type(test))
^
SyntaxError: invalid token
The final test using the string “003” resulted in an error.
literal_eval()
The results for literal_eval() show the numbers are converted to either an integer or a float, but it also does not like the string ‘003’.
from ast import literal_eval
test = "3"
test = literal_eval(test)
print(test)
print("The string x is now a ", type(test))
Output: 3
The string x is now a <class ‘int’>
Output: 3.0
The string x is now a <class ‘float’>
Output: 3.2
The string x is now a <class ‘float’>
Output: -3
The string x is now a <class ‘int’>
^
SyntaxError: invalid token
Again we see the final test using the string “003” resulted in an error.
6 - FAQ
There are common questions asked about how to convert a string to an int in python. Here is a range of frequently asked questions with solutions and example python code.
How do you convert a string to an integer in Python?
You can convert a string to an integer in Python using the int() function.
What happens if the string cannot be converted to an integer?
If the string cannot be converted to an integer then a ValueError will occur. Use try and except to catch errors.
Can you convert a string with a different base to an integer?
Yes, you can convert a string with a different base to an integer by using the int().