Python: Cannot understand why the error - cannot concatenate 'str' and 'int' object ?

The error "cannot concatenate 'str' and 'int' object" occurs when you try to combine a string and an integer without proper type conversion. This happens because Python doesn't automatically convert between string and integer types during concatenation.

Understanding the Error

When you use string formatting with %d, Python expects an integer value. If you try to perform arithmetic operations directly in the format string without proper grouping, it can cause concatenation issues.

Incorrect Approach

# This might cause issues with operator precedence
for num in range(5):
    print("%d" % num+1)  # Error: trying to concatenate formatted string with int

Correct Approach

The solution is to group the arithmetic operation in parentheses to ensure proper evaluation order ?

for num in range(5):
    print("%d" % (num+1))
1
2
3
4
5

Alternative Solutions

Using f-strings (Python 3.6+)

for num in range(5):
    print(f"{num+1}")
1
2
3
4
5

Using str() Function

for num in range(5):
    print(str(num+1))
1
2
3
4
5

Why This Error Occurs

The %d formatter converts the value to a string representation of an integer. Without parentheses, Python interprets "%d" % num + 1 as (("%d" % num) + 1), which attempts to concatenate a formatted string with the integer 1.

Conclusion

Always use parentheses around arithmetic expressions in string formatting operations. Modern Python code should prefer f-strings for better readability and performance over older % formatting.

---
Updated on: 2026-03-24T20:38:07+05:30

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements