Python 没有“+”运算符的字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18842779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:02:50  来源:igfitidea点击:

String concatenation without '+' operator

pythonstringoptimizationconcatenationstring-concatenation

提问by ibrahim

I was playing with python and I realized we don't need to use '+' operator to concatenate strings unless it is used with values.

我在玩 python,我意识到我们不需要使用 '+' 运算符来连接字符串,除非它与值一起使用。

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:

现在我有两个问题:

  1. Why statement 3 does not work while statement 1 does?
  2. Is there any technical difference such as calculation speed etc. between statement 1 and 2?
  1. 为什么语句 3 不起作用而语句 1 起作用?
  2. 语句 1 和语句 2 之间是否存在计算速度等技术差异?

采纳答案by TerryA

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

允许多个相邻的字符串文字(由空格分隔),可能使用不同的引用约定,它们的含义与其连接相同。因此,“hello”'world' 等价于“helloworld”。



Statement 3 doesn't work because:

语句 3 不起作用,因为:

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.

这是错误永远不应该静默传递的完美示例如果我想"bill"成为争论者baz怎么办?我忘记了逗号,但没有出现错误。相反,发生了串联。

回答by user2357112 supports Monica

This is implicit string literal concatenation. It only happens with string literals, not variables or other expressions that evaluate to strings. There used to be a (tiny) performance difference, but these days, the peephole optimizer should render the forms essentially equivalent.

这是隐式字符串文字连接。它只发生在字符串文字上,而不是变量或其他计算为字符串的表达式。曾经有一个(微小的)性能差异,但现在,窥视孔优化器应该使表单基本相同。

回答by Hyperboreus

To answer your second question: There is no difference at all (at least with the implementation I use). Disassembling both statements, they are rendered as LOAD_CONST STORE_FAST. They are equivalent.

回答你的第二个问题:根本没有区别(至少在我使用的实现中)。反汇编这两个语句,它们被呈现为LOAD_CONST STORE_FAST. 它们是等价的。

回答by SuperNova

You can use %sas this is more efficient than using + sign.

您可以使用,%s因为这比使用 + 符号更有效。

>>> string2 = "%s %s" %('Hello', 'World')
>>> string2
'Hello World'

(OR)

(或者)



one more method is .format

另一种方法是 .format

>>> string2 = "{0} {1}".format("Hello", "World")
>>> string2
'Hello World'
>>> 

回答by shray

Statement 3 doesn't work as when you concatenate two string expressions to create a new string you need a '+' operator.

语句 3 不起作用,因为当您连接两个字符串表达式以创建一个新字符串时,您需要一个“+”运算符。

whereas in case of sting 1,2 and 4, adjacent literals separated by white spaces use different quoting conventions.Hence they are allowed making them print same as their concatenation.

而在 sting 1,2 和 4 的情况下,由空格分隔的相邻文字使用不同的引用约定。因此它们被允许使它们与它们的串联打印相同。

also, there won't be any significant or noticeable time difference in running those 2 operations.

此外,运行这两个操作不会有任何显着或明显的时间差异。

%%timeit -n 1
s1='ab'
s2='ba'
print(s1+s2)

o/p The slowest run took 17.08 times longer than the fastest. This could mean that an intermediate result is being cached. 57.8 μs ± 92.5 μs per loop (mean ± std. dev. of 7 runs, 1 loop each)

o/p 最慢的运行时间比最快的运行时间长 17.08 倍。这可能意味着正在缓存中间结果。每个循环 57.8 μs ± 92.5 μs(平均值 ± 标准偏差,7 次运行,每个循环 1 个)

%%timeit -n 1
s3='ab' 'ba'
print(s3)

o/p The slowest run took 4.86 times longer than the fastest. This could mean that an intermediate result is being cached. 25.7 μs ± 21 μs per loop (mean ± std. dev. of 7 runs, 1 loop each)

o/p 最慢的运行时间比最快的运行时间长 4.86 倍。这可能意味着正在缓存中间结果。每个循环 25.7 μs ± 21 μs(平均值 ± 标准偏差,7 次运行,每次 1 个循环)

回答by thiruvenkadam

Why statement 3 does not work while statement 1 does?

为什么语句 3 不起作用而语句 1 起作用?

Because, in the first statement, we are assigning some constant to a variable. Variable assignment is simple enough such that we can keep on putting multiple constants to a single variable and the assignment will still go through. The terms "hello"and "world"are two constants of same type. So, the statement worked.

因为,在第一条语句中,我们为变量分配了一些常量。变量赋值非常简单,我们可以继续将多个常量赋值给一个变量,并且赋值仍然会通过。项"hello""world"是两个相同类型的常量。因此,该声明有效。

If we do the following, we will get SyntaxError

如果我们执行以下操作,我们将得到 SyntaxError

string1 = "Hello" 1

The reason is that we supplied multiple constants in a single variable assignment. This confused python and it thrown it out as an error.

原因是我们在单个变量赋值中提供了多个常量。这混淆了python,并将其作为错误抛出。

The statement 3 is all about assigning a variable based on two variables. This will produce SyntaxErroras python don't know what it can do with 2 variables before assigning it to the variable.

语句 3 是关于基于两个变量分配一个变量。这将产生,SyntaxError因为在将它分配给变量之前,python 不知道它可以用 2 个变量做什么。

Is there any technical difference such as calculation speed etc. between statement 1 and 2?

语句 1 和语句 2 之间是否存在计算速度等技术差异?

Yes. The only technical difference is readability rather than anything else. Readability matters most in Python. For an untrained eye, "hello" "world"might look like the compiler would add the space to the strings. Which is not the case.

是的。唯一的技术区别是可读性而不是其他任何东西。可读性在 Python 中最重要。对于未经训练的眼睛,"hello" "world"可能看起来编译器会将空格添加到字符串中。事实并非如此。

However,

然而,

"hello" + "world"

is explicit and normal. Nearly always, Explicit is better than implicit.

是明确的和正常的。几乎总是,显式优于隐式。