How to Convert String into Integer in Python
3 min read
All data types in Python, including integers and strings, are objects. Often when writing Python code, you will need to convert one data type to another. For example, to perform a math operation on a number represented as a string, it needs to be converted into an integer.
In this article, we’ll show you how to convert a Python string to an integer.
int() function returns a decimal integer object from a given number or string. It takes the following form:
The function accepts two arguments:
x- String or number to be converted to an integer.
base- It represents the numeral system of the first argument. Its value can be 0 and 2–36. This argument is optional. If no base is given, the default is 10 (decimal integer).
Usually, integers are expressed in hexadecimal (base 16), decimal (base 10), octal (base 8), or binary (base 2) notation.
If the given string cannot be represented as an integer, the function will throw a
Converting a Python String into Integer
In Python, a ‘string’ is a list of characters which is declared using single (
'), double (
"), or triple quotes (
If a variable that contains only numbers is declared using quotes, its data type is set to String. Consider the following example:
days = "23" type(days)
type() function shows us that the
days variable is a
Let’s try to do a math operation on the variable:
Python will throw a
TypeError exception error because it cannot perform an addition calculation with string and integer:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
To convert a string representation of a decimal integer into an
int, pass the string to the
int() function, which returns a decimal integer:
days = "23"
days_int = int(days)
If you now try to do the math, the sum operation will be performed successfully:
If the number includes commas, marking off thousands, millions, etc., you need to remove the commas before passing the number to the
total = "1,000,000"
When converting strings that represent integers in different number systems, make sure you use the correct
For example, in the hexadecimal system, the number 54732 is represented as
D5CF. To convert it to a decimal integer you need to use base 16:
If you pass the
D5CF string to the
int() function without setting a base, it will throw a
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'D5CF'
In Python, you can convert a string to an integer using the
If you have any questions or feedback, feel free to leave a comment.