Fundamentals 3 min read
How Python’s + Operator Concatenates Strings (and Why Numbers Fail)
The article explains that in Python the + operator joins two strings into one, demonstrates this with code examples, and warns that adding a number to a string raises a TypeError, illustrating the rule with sample output and error messages.
Lisa Notes
Lisa Notes
Python “+” operator on strings
Using + between two string objects concatenates them into a single string.
str1 = "hello"
str2 = "world"
print(str1 + str2)Output: hello world Adding a string and an integer raises TypeError because Python does not support addition between a string and a numeric type.
str3 = "welcome"
num = 12
# print(str3 + num) # raises TypeErrorResulting traceback (escaped tag):
Traceback (most recent call last):
File "C:/Users/xuexi/Desktop/python/xuexi007.py", line 8, in <module>
print(str3 + num)
TypeError: can only concatenate str (not "int") to str
进程已结束,退出代码1Written by
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
0 followers
Reader feedback
How this landed with the community
Rate this article
Was this worth your time?
Discussion
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
