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

Loading

The error message:

TypeError: can only concatenate str (not "int") to str

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


1. Causes and Solutions

Cause 1: Trying to Concatenate a String and an Integer

Python does not allow direct concatenation of a string and an integer.

Incorrect Code:

age = 25
message = "I am " + age + " years old" # Error: Cannot concatenate str and int

Error Output:

TypeError: can only concatenate str (not "int") to str

Solution: Convert int to str Before Concatenation

message = "I am " + str(age) + " years old"
print(message) # Output: I am 25 years old

Cause 2: Using + Instead of , in print()

If you’re printing multiple values, use commas (,) instead of + to avoid type issues.

Incorrect Code:

age = 30
print("My age is " + age) # TypeError

Solution: Use a Comma (,) in print()

print("My age is", age)  # Works fine
# Output: My age is 30

Cause 3: Concatenating a Number Inside a Loop

When looping, if you append a number to a string incorrectly, a TypeError will occur.

Incorrect Code:

total = "Total: "
num = 100
total += num # Error: Trying to add int to str

Solution: Convert the Integer to a String

total += str(num)
print(total) # Output: Total: 100

Cause 4: Using join() with Non-String Elements

The join() method works only with strings, so if you try to join a list containing numbers, you’ll get a TypeError.

Incorrect Code:

numbers = [1, 2, 3]
result = "-".join(numbers) # TypeError: int in list

Solution: Convert All Elements to Strings

result = "-".join(map(str, numbers))
print(result) # Output: 1-2-3

Leave a Reply

Your email address will not be published. Required fields are marked *