字符串连接的变体?

Ulf*_*lfR 8 python string string-concatenation

字符串文字串联中的以下两个变体(带或不带加号):

  • 什么是首选方式?
  • 有什么不同?
  • 何时应该使用其中一种?
  • 是否应该使用它们,如果是这样,为什么?
  • join首选?

码:

>>> # variant 1. Plus
>>> 'A'+'B'
'AB'
>>> # variant 2. Just a blank space
>>> 'A' 'B'
'AB'
>>> # They seems to be both equal
>>> 'A'+'B' == 'A' 'B'
True
Run Code Online (Sandbox Code Playgroud)

Mik*_*ler 13

并置仅适用于字符串文字:

>>> 'A' 'B'
'AB'
Run Code Online (Sandbox Code Playgroud)

如果使用字符串对象:

>>> a = 'A'
>>> b = 'B'
Run Code Online (Sandbox Code Playgroud)

你需要使用不同的方法:

>>> a b
    a b
      ^
SyntaxError: invalid syntax

>>> a + b
'AB'
Run Code Online (Sandbox Code Playgroud)

+比将文字放在彼此旁边要明显得多.

第一种方法的一个用途是将长文本分成几行,并在源代码中保留缩进:

>>> a = 5
>>> if a == 5:
    text = ('This is a long string'
            ' that I can continue on the next line.')
>>> text
'This is a long string that I can continue on the next line.'
Run Code Online (Sandbox Code Playgroud)

''join() 是连接更多字符串的首选方法,例如在列表中:

>>> ''.join(['A', 'B', 'C', 'D'])
'ABCD'
Run Code Online (Sandbox Code Playgroud)