+ Python · 运算符
`+` 有两种用法:对数字做加法,对字符串、列表、元组等序列做拼接。就像把两堆东西合在一起——数字相加得到总和,序列拼接得到更长的序列。
怎么用
数字1 + 数字2 字符串1 + 字符串2 列表1 + 列表2
小例子
print(3 + 5)
print("hello" + " " + "world")
print([1, 2] + [3, 4])
print((1, 2) + (3, 4))
运行结果
8 hello world [1, 2, 3, 4] (1, 2, 3, 4)
对比:不同类型不能直接相加
print(3 + "5") # TypeError: unsupported operand type(s) for +: 'int' and 'str'
需要先转换类型:`3 + int("5")` 或 `str(3) + "5"`。常见使用场景
1. 数字累加: 总和 = 10 + 20 + 30 2. 字符串拼接(注意性能,大量拼接用 `join`): 问候 = "你好,我是" + 名字 3. 列表合并: 全部水果 = 水果1 + 水果2
提醒:- 对于列表,`+` 会创建一个新列表,不修改原列表。 - 对于字符串,大量拼接应使用 `''.join(list)`,因为 `+` 会每次创建新字符串,效率低。 - 集合不支持 `+`,应该用 `|`(并集)或 `.union()`。
官方文档:https://docs.python.org/zh-cn/3/reference/expressions.html#binary-arithmetic-operations
在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条