How to Convert Strings to Integers in Python

By 

•

Updated on

•

5 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

Python also accepts underscores between digits, the same grouping style you can use in numeric literals:

python
int("1_000_000")
output
1000000

Use the replace() 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 want to discard the fractional part of a decimal string, you can convert it to float first and then to int. The int() function truncates toward zero:

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

The result is 10 because int() discards the fractional part. Converting through float can lose precision for large values or values with many significant digits. For exact parsing of a decimal string before truncation, use int(Decimal(value)) after importing Decimal with from decimal import Decimal.

Check if a String Is an Integer

Sometimes you want to check a value before converting it, for example to show an error message instead of falling back to a default. The string method isdigit() returns True when every character in the string is a digit:

python
"42".isdigit()
output
True

The method does not understand signs, so a negative number fails the check even though int() accepts it:

python
"-42".isdigit()
output
False

isdigit() also returns True for some Unicode characters that int() cannot parse, such as the superscript two:

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

Because of these edge cases, the most reliable check is the conversion itself. Python has no built-in “try parse” function like some other languages, but a small helper does the same job. The function below returns the integer, or None when the string is not a valid integer:

python
def to_int(value):
    try:
        return int(value)
    except ValueError:
        return None

print(to_int("-42"))
print(to_int("abc"))
output
-42
None

The caller can now test the result with is None and decide how to handle invalid input.

Conclusion

Use int() to convert a string that contains a whole number into a Python integer, and catch ValueError for values that come from outside your code. For the reverse conversion, see how to convert an integer to a string in Python .

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 1000+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page