How to Convert a String to an Int in Python
int(text), for example int("42") returns 42. If the string is not a whole number, such as "3.7" or "abc", int() raises a ValueError.Text that comes from input(), a file or a web form is always a string, so you must convert it before doing arithmetic. The built-in int() function does that job. This is one case of type casting in Python, and it pairs naturally with reading user input.
The conversion is strict: the string may contain only an optional sign, digits and surrounding whitespace. Anything else fails loudly, which is good because it stops bad data from slipping into your calculations.
| Syntax | int(text) or int(text, base) |
|---|---|
| Returns | A new int |
| Fails with | ValueError when the text is not a whole number |
| Allowed extras | Leading and trailing whitespace, a + or - sign, underscores between digits |
The basic way: int() on a string
Pass the string to int() and use the result like any other number. The original string is not changed, because strings are immutable.
quantity = "12"
price = 4
print(int(quantity) * price)
print(int(" -7 "))
print(int("1_000"))Convert a string in another number base
Give int() a second argument to tell it the base of the text, from 2 to 36. With base 0 Python reads the prefix (0x, 0o, 0b) to decide.
print(int("ff", 16))
print(int("1010", 2))
print(int("0x1A", 0))Why int('3.7') fails and how to convert decimal strings
A string like "3.7" is a float, not a whole number, so int() refuses it. Convert to float first, then to int. Note that int() on a float cuts off the decimal part instead of rounding; see converting a float to an int for rounding options. If you need the float itself, read converting a string to a float.
Handle bad input safely with try and except
When the text comes from a user you cannot trust it. Wrap the conversion in try/except ValueError (see Python exceptions) and decide what to do with bad values: ask again, skip, or use a default.
def to_int(text, default=None):
try:
return int(text)
except ValueError:
return default
Quick comparison of the common cases
| String | `int()` result |
|---|---|
"42" | 42 |
" 42\n" | 42 (whitespace is ignored) |
"-5" | -5 |
"3.7" | ValueError |
"1,000" | ValueError (remove the comma first) |
"" | ValueError |
"٣" (Arabic-Indic digit) | 3 (Unicode decimal digits are accepted) |
Very long digit strings
Since Python 3.11, converting a decimal string with more than 4300 digits raises a ValueError to protect against denial-of-service attacks. This only matters for huge numbers, and the limit can be changed with sys.set_int_max_str_digits().
Examples you can run
Press Run, then edit the code and run it again.
Convert a list of string numbers and add them
Use a list comprehension to convert every item, then sum the results.
scores = ["80", "92", "75"]
numbers = [int(s) for s in scores]
print(numbers)
print(sum(numbers))Expected output[80, 92, 75]
247
Read a whole number from the user
input() always returns a string, so convert it before calculating.
age = int(input("Age: "))
print("Next year:", age + 1)Expected outputAge: 29
Next year: 30
Edge case: decimal strings and bad input
A helper that returns a default value instead of crashing.
def to_int(text, default=0):
try:
return int(text)
except ValueError:
return default
print(to_int("15"))
print(to_int("abc"))
print(to_int("3.7"))
print(int(float("3.7")))Expected output15
0
0
3
Common mistakes
Converting a decimal string directly
✗ Wrong
price = int("19.99")✓ Right
price = int(float("19.99"))
print(price)Convert with float() first, then decide how to turn it into a whole number.
Forgetting to convert input()
✗ Wrong
age = input("Age: ")
print(age + 1)✓ Right
age = int(input("Age: "))
print(age + 1)input() returns text. Wrap it in int() before doing maths.
Leaving thousands separators in the text
✗ Wrong
total = int("1,250")✓ Right
total = int("1,250".replace(",", ""))
print(total)Remove the commas with replace() before converting.
How to Convert a String to an Int in Python: questions people ask
How do I convert a string to an integer in Python?
Call int() with the string, for example int("42"). The string must contain only digits with an optional sign and whitespace.
Why do I get ValueError: invalid literal for int() with base 10?
The string is not a valid whole number, for example it has a decimal point, letters, commas or is empty. Clean the text or convert via float(), and catch the ValueError for untrusted input.
How do I convert a string to int and keep the decimal part?
You cannot keep it in an int. Use float("3.7") or decimal.Decimal("3.7") instead, because integers have no fractional part.
Keep learning
Step-by-step lessons:
Python CastingPython NumbersPython ValueError
Related:
How to Convert an Int to a String in PythonHow to Convert a String to a Float in PythonHow to Convert a Float to an Int in Python
More in converting data:
How to Convert an Int to a String in PythonHow to Convert a List to a String in PythonHow to Convert a String to a List in PythonHow to Convert a String to a Float in PythonHow to Convert a Float to an Int in PythonHow to Convert a List to a Dictionary in PythonHow to Convert a Tuple to a List in PythonHow to Convert a String to a Datetime in Python See all →