Last modified: Apr 09, 2025 By Alexander Williams
Fix TypeError: int + str in Python
Python is a flexible language. But mixing data types can cause errors. One common error is TypeError: unsupported operand type(s) for +: 'int' and 'str'.
This error happens when you try to add an integer and a string. Python does not allow this. You must convert one type to match the other.
Understanding the Error
The error occurs when using the +
operator. It can't add numbers and text. Here is an example:
age = 25
message = "I am " + age + " years old."
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Python expects both values to be the same type. The +
operator works differently for strings and numbers.
Common Causes
This error often happens in these cases:
1. Concatenating strings with numbers. Like in the example above.
2. Reading user input. The input()
function always returns a string.
3. Processing data from files. Numbers may be read as strings.
How To Fix the Error
There are simple ways to fix this. You can convert the types to match.
Method 1: Convert int to str
Use the str()
function. It converts numbers to strings.
age = 25
message = "I am " + str(age) + " years old."
print(message)
I am 25 years old.
Now it works. The number is converted to a string first.
Method 2: Use f-strings (Python 3.6+)
f-strings make string formatting easy. They handle type conversion automatically.
age = 25
message = f"I am {age} years old."
print(message)
I am 25 years old.
This is the cleanest solution. It works for all data types.
Method 3: Convert str to int
Sometimes you need numbers. Use int()
to convert strings to integers.
num1 = "10"
num2 = 20
total = int(num1) + num2
print(total)
30
Be careful. If the string is not a number, this will fail.
Best Practices
Follow these tips to avoid type errors:
1. Check variable types with type()
. This helps debug issues.
2. Use f-strings for string formatting. They are clear and safe.
3. Validate user input. Convert it to the right type early.
For more on Python errors, see our guide on How To Solve ModuleNotFoundError.
Conclusion
The TypeError happens when mixing types. Python can't add numbers and strings. Convert one type to match the other.
Use str()
or int()
for simple cases. Prefer f-strings for string formatting. Always check your variable types.
With these tips, you can fix this error fast. Happy coding!