Last modified: May 22, 2025 By Alexander Williams
Fix ValueError: Could Not Convert String to Int
The ValueError: could not convert string to int is a common error in Python. It happens when you try to convert a string to an integer, but the string contains invalid characters.
What Causes the Error?
This error occurs when using the int()
function on a string that isn't a valid number. The string might contain letters, symbols, or spaces.
# Example causing the error
num = int("123abc")
ValueError: invalid literal for int() with base 10: '123abc'
How to Fix the Error
Here are the best ways to fix this error in Python.
1. Check the String Before Converting
Use the isdigit()
method to verify if the string contains only digits.
value = "123"
if value.isdigit():
num = int(value)
else:
print("Invalid number")
2. Handle Empty Strings and Spaces
Trim whitespace using strip()
and check for empty strings.
value = " 123 "
cleaned = value.strip()
if cleaned and cleaned.isdigit():
num = int(cleaned)
3. Use Try-Except Block
Wrap the conversion in a try-except block to handle errors gracefully.
try:
num = int("123abc")
except ValueError:
print("Conversion failed")
Common Scenarios
This error often appears when reading user input or parsing files. Always validate data before conversion.
For similar issues with arrays, see our guide on Fix ValueError: Shapes Not Aligned in Python.
Working with Different Number Formats
If your string represents a float, convert it to float first, then to int.
value = "123.45"
num = int(float(value)) # First convert to float, then to int
Conclusion
The ValueError: could not convert string to int is easy to fix once you understand its causes. Always validate strings before conversion. Use proper error handling for robust code.
For more Python error solutions, check our articles on Fix ValueError: Array Element with Sequence and Fix ValueError: Inconsistent Input Samples.