As the error suggests, using the +
operator for concatenation is only valid if both sides are strings. Python uses string formatting instead of concatenation when mixing strings and variables. In modern Python (3.6+), your example can be simplified using f-strings:
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)
This format is easier to read, and avoids the TypeError
. Prior to Python 3.6, you would have needed to use the %
operator and sprintf
-style formatting:
name = "Alice"
age = 25
message = "My name is %s and I am %d years old." % (name, age)
print(message)
In addition to the official Python docs linked above, there is also a good tutorial at Real Python that discusses these techniques in more detail.