gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:38 25 4
gpt4 key购买 nike

我有一个变量 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'
>>>

关于python - 写值需要多行时如何给变量赋值(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3477592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com