Skip to main content
 首页 » 编程设计

python之写值需要多行时如何给变量赋值(python)

2025年05月04日10落叶

我有一个变量 x,我想为其分配一个很长的字符串。由于字符串很长,我将其拆分为 10 个子字符串。我想做这样的事情:

x = 
   'a very long string - part 1'+ 
   'a very long string - part 2'+ 
   'a very long string - part 3'+ 
                ... 
   'a very long string - part 10' 

但事实证明这是一个无效的语法。其有效语法是什么?

请您参考如下方法:

如果你想要一个没有换行符的字符串,你可以

>>> x = ( 
... 'a very long string - part 1' + 
... 'a very long string - part 2' + 
... 'a very long string - part 3' ) 
>>> x 
'a very long string - part 1a very long string - part 2a very long string - part 3' 
>>>  

+ 运算符对于 string literals 不是必需的:

2.4.2. String literal concatenation

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". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example:

re.compile("[A-Za-z_]"       # letter or underscore 
       "[A-Za-z0-9_]*"   # letter, digit or underscore 
      ) 

您的案例:

>>> x = ( 
... 'a very long string - part 1'  
... 'a very long string - part 2'  
... 'a very long string - part 3' ) 
>>> x 
'a very long string - part 1a very long string - part 2a very long string - part 3' 
>>>