How to Convert Strings to Integers in Python

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:
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 be0or any integer from2to36. 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:
days = "23"
type(days)The type() function shows that days is a string:
<class 'str'>If you try to add that string to an integer, Python raises a TypeError because the two values have different types:
print(days + 5)Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to strPass the string to int() to convert it:
days = "23"
days_int = int(days)
type(days_int)<class 'int'>The converted value can now be used in arithmetic:
print(days_int + 5)28Convert Strings with Spaces or Signs
The int() function ignores leading and trailing whitespace:
int(" 42 ")42It also accepts leading plus and minus signs:
int("-15")-15int("+15")15Remove Thousands Separators
If the number includes commas or other separators, remove them before passing the string to int():
total = "1,000,000"
int(total.replace(",", ""))1000000Python also accepts underscores between digits, the same grouping style you can use in numeric literals:
int("1_000_000")1000000Use 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:
int("D5CF", 16)54735Binary and octal strings work the same way:
int("1010", 2)10int("755", 8)493If the string includes a base prefix such as 0b, 0o, or 0x, use base=0 and Python will detect the base automatically:
int("0xff", 0)255If you pass a hexadecimal string without setting the base, Python tries to parse it as decimal and raises ValueError:
int("D5CF")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:
value = "abc"
try:
number = int(value)
except ValueError:
number = 0
print(number)0This 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:
int("10.5")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:
int(float("10.5"))10The 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:
"42".isdigit()TrueThe method does not understand signs, so a negative number fails the check even though int() accepts it:
"-42".isdigit()Falseisdigit() also returns True for some Unicode characters that int() cannot parse, such as the superscript two:
"²".isdigit()Trueint("²")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:
def to_int(value):
try:
return int(value)
except ValueError:
return None
print(to_int("-42"))
print(to_int("abc"))-42
NoneThe 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 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