Skip to content

ValueError: invalid literal for int()

Quick summary

You called int(), float(), or similar with a string that cannot be parsed as a number — Python raises ValueError with the invalid input.

Why this happens

  • The string contains non-numeric characters, letters, or symbols that cannot be part of a number

  • The string has leading/trailing whitespace or formatting characters that int() cannot handle

  • The string represents a float like '3.14' but you are converting with int() which expects an integer literal

Minimal example

✗ Broken code
value = '42abc'
num = int(value)  # ValueError: invalid literal for int() with base 10: '42abc'
✓ Fixed code
value = '42abc'
try:
    num = int(value)
except ValueError:
    num = int(''.join(c for c in value if c.isdigit()))  # extract digits
print(num)  # 42

Catching ValueError and extracting only the digit characters lets you handle malformed numeric strings gracefully.

How to diagnose

  • Print the exact string value with repr() to see hidden characters like whitespace or non-breaking spaces

  • Strip whitespace and check if the string matches a numeric pattern before converting

  • Try converting with float() first if the input might contain a decimal point, then int() the result

How to fix

  • Clean the string with strip() and remove non-numeric characters before calling int() or float()

  • Use a try/except ValueError to catch the conversion failure and provide a user-friendly error message

  • Convert via float() first for decimal strings, then int(float_value) if you need an integer result

How to prevent

  • Validate user input with a regex or isdigit() check before attempting numeric conversion

  • Use try/except around all string-to-number conversions and handle ValueError with clear feedback

Related Resources

Related Glossary

Related Lessons

← Back to language