TypeError: can only concatenate str (not "int") to str
TypeError: can only concatenate str (not "int") to str in Python means you used + between a string and a number. Python will not guess whether you meant text or arithmetic.
How do I fix TypeError: can only concatenate str (not "int") to str?
TypeError: can only concatenate str (not "int") to str means you used + between a string and an integer. Python will not guess if you want text or maths. To build a message, use an f-string like f"You scored {score} points". To do arithmetic on input() or file data, convert it first with int() or float().
- 1. Find the + lineLook at each + on the failing line. The left side is a str and the right side is an int.
- 2. Use f-strings for textReplace "Score: " + score with f"Score: {score}". The f-string converts the number for you.
- 3. Convert input() valuesinput() and file lines are always strings. Use int(input(...)) before adding numbers to them.
What does TypeError: can only concatenate str (not "int") to str mean?
+ means concatenation for strings and addition for numbers, and Python refuses to mix them. The message tells you the left side is a str and the right side is an int. The reverse order, 5 + "5", gives "unsupported operand type(s) for +: 'int' and 'str'" — same bug, other way round.
Why does TypeError: can only concatenate str (not "int") to str happen?
1. Building a message with a number in it
The most common case — gluing a count or score into a sentence.
Breaks
print("You scored " + score + " points")Works
print(f"You scored {score} points")2. input() always returns a string
Even when the user types 5, input() gives you "5". Adding to it is concatenation, not arithmetic.
Breaks
age = input("Age: ")
print(age + 1)Works
age = int(input("Age: "))
print(age + 1)3. Numbers read from a file or CSV
Everything read from text is text until you convert it.
Breaks
count = f.readline().strip()
print(count + 1)Works
count = int(f.readline().strip())
print(count + 1)How to find it in your own code
Decide what you want: text or a number. For text, use an f-string — it converts automatically and reads better than str() everywhere. For arithmetic, convert the string with int() or float() as early as possible, right where it enters the program.
Try it: fix this bug
easyformat_price(5) crashes: TypeError: can only concatenate str (not "int") to str.
def format_price(amount):
return "$" + amountMore challenges with this error
Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.