TypeError: can only concatenate str (not "int") to str
What it means
You used + to join a string with something that is not a string, here a whole number. Python does not turn numbers into text on its own, because "5" + 3 could mean "53" or 8. Convert the number first, or use an f-string.
1. Joining text and a number with `+`
This raises the error
Broken
age = 25
print("I am " + age + " years old")
Output
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: can only concatenate str (not "int") to str
The fix
Fixed
age = 25
print(f"I am {age} years old")
Output
I am 25 years old
An f-string puts the value into the text for you. "I am " + str(age) + " years old" works too.
2. A calculated amount added to text
This raises the error
Broken
price = 4.5
quantity = 3
print("Total: " + price * quantity)
Output
Traceback (most recent call last): File "<exec>", line 3, in <module> TypeError: can only concatenate str (not "float") to str
The fix
Fixed
price = 4.5
quantity = 3
print(f"Total: {price * quantity:.2f}")
Output
Total: 13.50
The result of price * quantity is a float, so the message says not "float". The f-string turns it into text, and :.2f shows two decimal places.
3. Building a string from numbers in a loop
This raises the error
Broken
digits = [3, 1, 4]
code = ""
for d in digits:
code = code + d
print(code)
Output
Traceback (most recent call last): File "<exec>", line 4, in <module> TypeError: can only concatenate str (not "int") to str
The fix
Fixed
digits = [3, 1, 4]
code = ""
for d in digits:
code = code + str(d)
print(code)
Output
314
Each number must become text before it can join the string. "".join(str(d) for d in digits) does the same in one line.
When you see this error, check
- Wrap numbers in
str()before joining them to text with+. - Prefer f-strings, like
f"Score: {score}". print()accepts several values separated by commas and converts them itself:print("Age:", age).- If you meant to add numbers, convert the text instead:
int("5") + 3.
Related errors
All Python errors · How to read a traceback · Step through your code