use*_*349 35 python string concatenation
我有一些字符串要连接,结果字符串将很长.我也有一些变量要连接.
如何组合字符串和变量,以便结果是多行字符串?
以下代码抛出错误.
str = "This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3" ;
Run Code Online (Sandbox Code Playgroud)
我也尝试过这个
str = "This is a line" \
str1 \
"This is line 2" \
str2 \
"This is line 3" ;
Run Code Online (Sandbox Code Playgroud)
请建议一种方法来做到这一点.
Bry*_*ley 54
有几种方法.一个简单的解决方案是添加括号:
strz = ("This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3")
Run Code Online (Sandbox Code Playgroud)
如果您想在单独的一行上显示每个"行",则可以添加换行符:
strz = ("This is a line\n" +
str1 + "\n" +
"This is line 2\n" +
str2 + "\n" +
"This is line 3\n")
Run Code Online (Sandbox Code Playgroud)
小智 13
Python不是php,你不需要$在变量名之前放置.
a_str = """This is a line
{str1}
This is line 2
{str2}
This is line 3""".format(str1="blabla", str2="blablabla2")
Run Code Online (Sandbox Code Playgroud)
从Python 3.6开始,您可以使用所谓的“格式化字符串”(或“ f字符串”)轻松地将变量插入字符串中。只需f在字符串前面添加一个,然后将变量写在花括号({})内,如下所示:
>>> name = "John Doe"
>>> f"Hello {name}"
'Hello John Doe'
Run Code Online (Sandbox Code Playgroud)
要分割一个长字符串到多行包围零件用括号(()),或使用一个多行字符串(由三个双引号内的字符串"""或'''不是一个)。
字符串周围带有括号,您甚至可以将它们连接起来,而无需在它们+之间进行登录:
a_str = (f"This is a line \n{str1}\n"
f"This is line 2 \n{str2}\n"
"This is line 3") # no variable here, so no leading f
Run Code Online (Sandbox Code Playgroud)
提提您:如果一行中没有变量,则不需要f该行的前导。
提提您:您可以\在每行的末尾使用反斜杠()而不是括号将相同的结果归档,但是对于PEP8,您应该更倾向于使用括号作为行继续:
通过将表达式包装在括号中,可以将长行分成多行。应优先使用这些,而不是使用反斜杠进行行连续。
在多行字符串中,您不需要显式插入\n,Python会为您处理:
a_str = f"""This is a line
{str1}
This is line 2
{str2}
This is line 3"""
Run Code Online (Sandbox Code Playgroud)
提提您:请确保您正确对齐代码,否则每行前面都会有空白。
顺便说一句:您不应该调用变量,str因为那是数据类型本身的名称。
格式化字符串的来源: