引号内的Python字符串赋值

Vai*_*pal 2 python string

对Python行为感到困惑.考虑这些例子:

>>>a = "ww" "xx"
>>>print(a)
wwxx

>>>b = "yy" "xx"
>>>print(b)
yyxx

>>>c = a b
  File "<stdin>", line 1
    c = a b
          ^ 
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我期待着一个结果wwxxyyxx.

但是出现了语法错误.

它们之间是否有任何区别(字符串文字和字符串); 两者都是str类型.

Chr*_*nig 7

直接取自Python Docs Tutorial:

两个或多个彼此相邻的字符串文字(即引号之间的字符串)会自动连接.

>>> 'Py' 'thon'
'Python'
Run Code Online (Sandbox Code Playgroud)

这仅适用于两个文字,而不是变量或表达式:

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  ...
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

如果要连接变量或变量和文字,请使用+:

>>> prefix + 'thon'
'Python'
Run Code Online (Sandbox Code Playgroud)

当您想要断开长字符串时,此功能特别有用:

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
Run Code Online (Sandbox Code Playgroud)