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 tutorial, we’ll show you how to convert a Python string to an integer.

Python int() Function

The built-in int() function returns a decimal integer object from a given number or string. It takes the following form:

int(x, base=10)

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. 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 argument cannot be represented as an integer, the function will throw a ValueError exception.

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)

The type() function shows us that days is a String object.

<type 'str'>

Let’s try to do a math operation on the variable:

print(days+5)

Python will throw a TypeError exception error because we 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 int, pass the string to the int() function, which returns a decimal integer:

days = "23"
<type 'int'>

If you now try to do the math, the sum operation will be performed successfully:

print(days_int+5)
28

If the number includes commas, marking off thousands,  millions, etc., you need to remove the commas before passing the number  to the int() function:

total = "1,000,000"
1000000

When converting strings that represent integers in different number systems, make sure you use the correct base.

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:

int("D5CF", 16)
54735

If you pass the D5CF string to the int() function without setting a base, it will throw a ValueError exception:

int("D5CF")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'D5CF'

Conclusion

In Python, you can convert a string to an integer using the int() function.