没有“+"运算符的字符串连接 [英] String concatenation without '+' operator
问题描述
我在玩 python,我意识到我们不需要使用+"运算符来连接静态字符串.但是如果我将它分配给一个变量,它就会失败.
例如:
string1 = 'Hello' 'World' #1 工作正常string2 = 'Hello' + 'World' #2 也可以正常工作string3 = '你好'string4 = '世界'string5 = string3 string4 #3 导致语法错误string6 = string3 + string4 #4 工作正常
现在我有两个问题:
- 为什么语句 3 不起作用而语句 1 起作用?
- 语句 1 和语句 2 之间是否存在计算速度等技术差异?
来自 文档:
<块引用>允许多个相邻的字符串文字(由空格分隔),可能使用不同的引用约定,它们的含义与其连接相同.因此,hello"'world' 等价于helloworld".
<小时>
语句 3 不起作用,因为:
<块引用>在运行时必须使用‘+’运算符来连接字符串表达式.
请注意,文档中子标题的标题也是字符串文字连接".这仅适用于字符串文字,不适用于其他对象.
<小时>可能没有区别.如果有,它可能非常小,任何人都不应该担心.
<小时>另外,请理解这可能存在危险:
<预><代码>>>>def foo(bar, baz=None):...返回栏...>>>foo("鲍勃"... 账单")'鲍勃'这是错误永远不应该静默传递的完美示例.如果我希望 "bill"
作为参数 baz
怎么办?我忘记了逗号,但没有出现错误.相反,发生了串联.
I was playing with python and I realized we don't need to use '+' operator to concatenate static strings. But it fails if I assign it to a variable.
For example:
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
Now I have two questions:
- Why statement 3 does not work while statement 1 does?
- Is there any technical difference such as calculation speed etc. between statement 1 and 2?
From the docs:
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".
Statement 3 doesn't work because:
The ‘+’ operator must be used to concatenate string expressions at run time.
Notice that the title of the subheader in the docs is "string literal concatenation" too. This only works for string literals, not other objects.
There's probably no difference. If there is, it's probably extremely tiny and nothing that anyone should worry about.
Also, understand that there can be dangers to this:
>>> def foo(bar, baz=None):
... return bar
...
>>> foo("bob"
... "bill")
'bobbill'
This is a perfect example of where Errors should never pass silently. What if I wanted "bill"
to be the argument baz
? I have forgotton a comma, but no error is raised. Instead, concatenation has taken place.
这篇关于没有“+"运算符的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!