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
Lisa Notes
How Python’s + Operator Concatenates Strings (and Why Numbers Fail)

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 TypeError

Resulting 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
进程已结束,退出代码1
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonTypeErrorProgramming BasicsString concatenationArithmetic operators
Lisa Notes
Written 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

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.