How to Fix: TypeError: can only concatenate str (not “int”) to str

3D visualization of a failed attempt to weld a wooden number block to a metal text beam, representing a concatenation TypeError.

Python is strongly typed. It refuses to guess what you mean if you try to combine different data types, often leading to a TypeError can only concatenate string error. It doesn’t know if "Age: " + 25 should be math (impossible) or text combining.

Problem Code:

age = 25
message = "I am " + age + " years old."
# CRASH! TypeError: can only concatenate str (not "int") to str

Fix 1: The Modern Way (f-strings)

This is the best, most readable way. Just put an f before the quote and use curly braces {}. Python handles the conversion automatically.

age = 25
message = f"I am {age} years old."
print(message)

Fix 2: The Manual Way (str())

If you must use + to combine them, you have to manually convert the number to a string first.

age = 25
message = "I am " + str(age) + " years old."
print(message)

Summary

Never try to + a string and a non-string. Always use f-strings for easy, error-free text formatting.

Similar Posts

Leave a Reply