How to Fix TypeError: cannot concatenate str and int objects in Python

 


 

 What Does This Error Mean?

This error occurs when you try to combine (concatenate) a string (str) with an integer (int) directly using the + operator.

 Example That Triggers the Error

age = 25
print("I am " + age + " years old")  #  TypeError

Output:

TypeError: cannot concatenate 'str' and 'int' objects

 How to Fix It

You need to convert the integer to a string before concatenation.

 Option 1: Use str()

age = 25
print("I am " + str(age) + " years old")  #  Works

 Option 2: Use f-strings (Python 3.6+)

age = 25
print(f"I am {age} years old")  #  Clean and readable

 Option 3: Use format()

age = 25
print("I am {} years old".format(age))  #  Works well

 Option 4: Use Commas in print()

age = 25
print("I am", age, "years old")  #  Python handles conversion automatically

Why This Happens

Python does not automatically convert integers to strings during concatenation because it's a strongly typed language. Mixing incompatible types without conversion causes a TypeError.

Pro Tip

If you work with user input or variables that can change types, always validate or convert explicitly:

user_input = 10
if isinstance(user_input, int):
    user_input = str(user_input)
print("Input was: " + user_input)

Summary Table

Problem Fix
"str" + int Use str(int)
Combine multiple data types Use f-strings or format()
Confused by error message Remember: + only works for same types

0 Comments:

Post a Comment