编程语言
首页 > 编程语言> > python – 没有”运算符的字符串连接

python – 没有”运算符的字符串连接

作者:互联网

我正在玩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之间是否存在任何技术差异,例如计算速度等?

解决方法:

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”.

声明3不起作用,因为:

The ‘+’ operator must be used to concatenate string expressions at run time.

请注意,文档中子标题的标题也是“字符串文字串联”.这仅适用于字符串文字,而不适用于其他对象.

可能没什么区别.如果有,它可能非常小,没有人应该担心.

另外,要明白这可能存在危险:

>>> def foo(bar, baz=None):
...     return bar
... 
>>> foo("bob"
... "bill")
'bobbill'

这是错误永远不会无声传递的完美示例.如果我想让“账单”成为baz的争论怎么办?我有一个逗号,但没有错误.相反,连接已经发生.

标签:python,string,concatenation,optimization,string-concatenation
来源: https://codeday.me/bug/20190916/1807319.html