我有一些字符串要连接,并且结果字符串将相当长。我还有一些变量需要连接。
如何组合字符串和变量,使结果成为多行字符串?
下面的代码引发错误。
str = "This is a line" + str1 + "This is line 2" + str2 + "This is line 3" ;
我也试过了
str = "This is a line" \ str1 \ "This is line 2" \ str2 \ "This is line 3" ;
请提出一个方法来做这件事。
我将添加所有需要连接到列表的内容,然后在换行符上将其连接起来。
my_str = '\n'.join(['string1', variable1, 'string2', variable2])
Python 不是 php,您不需要将 $放在变量名之前。
$
a_str = """This is a line {str1} This is line 2 {str2} This is line 3""".format(str1="blabla", str2="blablabla2")
有几种方法,一个简单的解决办法是加上括号:
strz = ("This is a line" + str1 + "This is line 2" + str2 + "This is line 3")
如果你想让每一行都单独显示,你可以添加换行符:
strz = ("This is a line\n" + str1 + "\n" + "This is line 2\n" + str2 + "\n" + "This is line 3\n")
从 Python 3.6开始,您可以使用所谓的“格式化字符串”(或“ f 字符串”)轻松地将变量插入到字符串中。只需在字符串前面添加一个 f,并在花括号({})中写入变量,如下所示:
f
{}
>>> name = "John Doe" >>> f"Hello {name}" 'Hello John Doe'
用 括号(())将一个长字符串拆分为多行,或者使用 多行字符串多行字符串(由三个引号 """或 '''而不是一个引号包围的字符串)。
()
"""
'''
在你的字符串周围加上圆括号,你甚至可以连接它们,而不需要在它们之间加上 +符号:
+
a_str = (f"This is a line \n{str1}\n" f"This is line 2 \n{str2}\n" f"This is line 3") # no variable in this line, so a leading f"" is optional but can be used to properly align all lines
很高兴知道: 如果一行中没有变量,就不需要该行的前导 f。
很高兴知道: 你可以在每一行的末尾使用反斜杠(\)来存档相同的结果,而不是使用圆括号,但是相应地,对于 PEP8,你应该更喜欢使用圆括号作为行的延续:
\
通过在括号中包装表达式,可以将长行分割成多行。这些选项应优先使用,而不是使用反斜杠作为行的延续。
在多行字符串中,您不需要显式插入 \n,Python 会为您解决这个问题:
\n
a_str = f"""This is a line {str1} This is line 2 {str2} This is line 3"""
很高兴知道: 只要确保正确对齐代码,否则每行前面都会有空白。
顺便说一句: 您不应该调用变量 str,因为那是数据类型本身的名称。
str
格式化字符串的来源: