Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python: Can not understand why I am getting the error: Can not concatenate 'int' and 'str' object
This error occurs when Python tries to concatenate (combine) an integer and a string using the + operator. Python cannot automatically convert between these data types during concatenation operations.
Common Cause of the Error
The error typically happens when using string formatting with %d placeholder. If you write %d % i + 1, Python interprets this as trying to add the integer 1 to the formatted string result.
Incorrect Code (Causes Error)
i = 5
# This causes the error - operator precedence issue
print("Num %d" % i + 1)
Solution: Use Parentheses
Wrap the arithmetic operation in parentheses to ensure it happens before string formatting ?
i = 5
print("Num %d" % (i + 1))
Num 6
Alternative Solutions
Using f-strings (Recommended)
i = 5
print(f"Num {i + 1}")
Num 6
Using .format() Method
i = 5
print("Num {}".format(i + 1))
Num 6
Manual Type Conversion
i = 5
print("Num " + str(i + 1))
Num 6
Understanding Operator Precedence
The root cause is operator precedence. The % operator has higher precedence than +, so Python evaluates "Num %d" % i first, then tries to add 1 to the resulting string.
| Expression | Python Interprets As | Result |
|---|---|---|
"Num %d" % i + 1 |
("Num %d" % i) + 1 |
Error: str + int |
"Num %d" % (i + 1) |
"Num %d" % (i + 1) |
Works correctly |
Conclusion
Use parentheses around arithmetic operations in string formatting to avoid concatenation errors. Modern Python code should prefer f-strings for cleaner, more readable string formatting.
