TypeError: can only concatenate str (not “int”) to str
Traceback (most recent call last):
File "shelf.py", line 2, in <module>
print("Price: " + price)
~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "int") to strNotice the squiggles under the line. Python is pointing at the + — that’s where the trouble is, not the variable.
What Python is actually saying
The + symbol does two different jobs depending on what’s on either side of it.
- Between two numbers, it adds:
2 + 3gives5 - Between two pieces of text, it joins:
"Rose" + "Serum"gives"RoseSerum"
Give it one of each and it has no idea which job you meant. Rather than guess, it stops.
Other languages would quietly turn the number into text for you. Python won’t, on purpose — silent guessing is how bugs get buried.
Fix 1: convert the number to text
price = 49
print("Price: R" + str(price))Price: R49str() turns a number into text. Now both sides of the + are text, so + knows to join them.
Fix 2: use an f-string (better)
price = 49
print(f"Price: R{price}")Price: R49Put an f before the opening quote, then drop any variable inside { }. No conversion, no +, and it reads like a sentence.
f-strings handle whatever you put in them, so this problem stops happening at all.
Where this bites hardest
input() always returns text — even when the person typed digits:
age = input("How old are you? ")
print(age + 1) # TypeErrorConvert it first:
age = int(input("How old are you? "))
print(age + 1)What to check, in order
- Look at what’s on either side of the
+ - Is one text and one a number?
- Did that value come from
input()? - Reach for an f-string rather than
+
Remember this
Python never quietly changes a value’s type for you. When + complains, one side is text and one is a number, and you get to decide which one changes.
Thirty errors, thirty fixes, in the Python Troubleshooting Handbook.