不带“+”操作的字符串连接

2024-05-29 02:49:35 发布

您现在位置: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

现在我有两个问题:

  1. 为什么陈述3不起作用而陈述1起作用?
  2. 报表1和报表2之间是否存在计算速度等技术差异?

Tags: 字符串helloworld报表运算符alsoworks意识
3条回答

回答你的第二个问题:根本没有区别(至少在我使用的实现上)。分解这两个语句后,它们将呈现为LOAD_CONST STORE_FAST。它们是等价的。

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'

这是一个完美的例子,说明错误永远不应该悄无声息地传递。如果我想让"bill"作为参数baz,会怎么样?我放弃了逗号,但没有引起错误。相反,发生了连接。

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

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

(或)


还有一种方法是.format

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

相关问题 更多 >

    热门问题