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.
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
进程已结束,退出代码1Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
