ValueError: invalid literal for int() with base 10 is raised when you pass a string to int() and that string does not represent a valid integer. Common cases are strings with letters, spaces, decimal points, or empty input. This guide explains why it happens and how to fix or avoid it.
What this error means
int(s) expects a string that looks like an integer in the given base (default 10): optional sign and digits, nothing else. So int("42") works; int("42.0"), int(" 42 ") (in older Python), int("abc"), or int("") can raise ValueError: invalid literal for int() with base 10: '…'. For float conversion issues see ValueError: could not convert string to float.
Common causes
- Non-numeric characters. The string contains letters or symbols (e.g.
"twenty","12.5","$100").int()does not parse those. - Spaces. Leading or trailing spaces can cause errors. Use
.strip()before converting. - Decimal point.
int("3.14")fails;int()does not parse floats. Useint(float("3.14"))if you want to truncate. - Empty string or user input. Empty input or non-numeric input from
input()will raise if passed directly toint().
Example that causes the error
num = int("twenty") # ValueError
num = int("19.99") # ValueError: decimal point
num = int(" 42 ") # May fail in some contexts; strip first
Fix 1: strip and validate
s = " 25 "
num = int(s.strip()) # OK
# Optional: check before converting
s = "25"
if s.strip().lstrip('-').isdigit():
num = int(s)
else:
print("Not a valid integer")
Fix 2: handle user input with try-except
user_input = input("Enter a number: ")
try:
num = int(user_input.strip())
print(f"You entered: {num}")
except ValueError:
print("That's not a valid integer.")
Fix 3: float string to integer
To turn a string like "19.99" into an integer, convert to float first, then to int (truncates toward zero):
price = "19.99"
num = int(float(price)) # 19
Next steps: Errors & Exceptions · ValueError: invalid float · TypeError: int and str