How to Convert Strings to Integers in Python

By 

Updated on

4 min read

Python Convert String into Int

When a number comes from user input, a file, an environment variable, or an API response, Python often receives it as a string. Before you can use that value in arithmetic, comparisons, or range checks, you need to convert it to an integer.

This article explains how to convert Python strings to integers with the built-in int() function and how to handle the most common conversion errors.

Python int() Function

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

python
int(x, base=10)

The function accepts two arguments:

  • x - The string or number to convert to an integer.
  • base - The numeral system used by the string. The value can be 0 or any integer from 2 to 36. If you omit it, Python uses base 10.

Most integer strings use decimal notation, but int() can also parse binary, octal, and hexadecimal strings when you pass the correct base.

If the string cannot be converted to an integer, Python raises a ValueError exception.

Convert a String to an Integer

In Python, strings are text values declared with single quotes, double quotes, or triple quotes. A value that looks like a number is still a string when it is wrapped in quotes:

python
days = "23"
type(days)

The type() function shows that days is a string:

output
<class 'str'>

If you try to add that string to an integer, Python raises a TypeError because the two values have different types:

python
print(days + 5)
output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Pass the string to int() to convert it:

python
days = "23"
days_int = int(days)
type(days_int)
output
<class 'int'>

The converted value can now be used in arithmetic:

python
print(days_int + 5)
output
28

Convert Strings with Spaces or Signs

The int() function ignores leading and trailing whitespace:

python
int("  42  ")
output
42

It also accepts leading plus and minus signs:

python
int("-15")
output
-15
python
int("+15")
output
15

Remove Thousands Separators

If the number includes commas or other separators, remove them before passing the string to int():

python
total = "1,000,000"
int(total.replace(",", ""))
output
1000000

Use this pattern only when you know the separator format. For user-facing data from different locales, validate the input before converting it.

Convert Binary, Octal, and Hexadecimal Strings

When converting strings from another numeral system, pass the correct base.

For example, the hexadecimal value D5CF is 54735 in decimal:

python
int("D5CF", 16)
output
54735

Binary and octal strings work the same way:

python
int("1010", 2)
output
10
python
int("755", 8)
output
493

If the string includes a base prefix such as 0b, 0o, or 0x, use base=0 and Python will detect the base automatically:

python
int("0xff", 0)
output
255

If you pass a hexadecimal string without setting the base, Python tries to parse it as decimal and raises ValueError:

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

Handle Invalid Input

Use try and except when the string may not contain a valid integer:

python
value = "abc"

try:
    number = int(value)
except ValueError:
    number = 0

print(number)
output
0

This pattern is useful when reading values from forms, files, command-line arguments, or environment variables.

Decimal strings such as "10.5" are not valid integer strings:

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

If you need to handle a decimal number, convert it to float first and then to int. Be aware that int() truncates the decimal part:

python
int(float("10.5"))
output
10

Conclusion

Use int() to convert a string that contains a whole number into a Python integer. For values that come from outside your code, validate the input and catch ValueError so your program can handle bad data cleanly.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page