【发布时间】:2013-09-21 11:23:01
【问题描述】:
我在玩 python,我意识到我们不需要使用 '+' 运算符来连接静态字符串。但是如果我将它分配给一个变量,它就会失败。
例如:
string1 = 'Hello' 'World' #1 works fine
string2 = 'Hello' + 'World' #2 also works fine
string3 = 'Hello'
string4 = 'World'
string5 = string3 string4 #3 causes syntax error
string6 = string3 + string4 #4 works fine
现在我有两个问题:
- 为什么语句 3 不起作用而语句 1 起作用?
- 语句1和语句2有计算速度等技术差异吗?
【问题讨论】:
-
这和 C/C++ 类似,
"hello " "world"会自动连接在一起 -
有一个关于这种行为的错误报告,但它被拒绝了,因为它是设计使然:legacy.python.org/dev/peps/pep-3126
-
Pylint 对某些情况下此语言功能现在容易出错的情况发出警告:
implicit-str-concat-in-sequence。从 Pylint 2.2 开始可用:pylint.pycqa.org/en/stable/whatsnew/2.2.html
标签: python string optimization concatenation string-concatenation