繁体   English   中英

在多行中连接python中的字符串

[英]Concatenate strings in python in multiline

我有一些字符串要连接,结果字符串会很长。 我还有一些要连接的变量。

如何组合字符串和变量,以便结果是多行字符串?

以下代码抛出错误。

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" ;

请提出一种方法来做到这一点。

有几种方法。 一个简单的解决方案是添加括号:

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 不是 php,您无需将$放在变量名之前。

a_str = """This is a line
       {str1}
       This is line 2
       {str2}
       This is line 3""".format(str1="blabla", str2="blablabla2")

使用格式化字符串的 Python 3 解决方案

Python 3.6 开始,您可以使用所谓的“格式化字符串”(或“f 字符串”)轻松地将变量插入到您的字符串中。 只需在字符串前面添加一个f并将变量写入大括号 ( {} ) 中,如下所示:

>>> name = "John Doe"
>>> f"Hello {name}"
'Hello John Doe'

要将长字符串拆分为多行,请使用括号( () ) 或使用多行字符串(由三个引号"""'''而不是一个引号包围的字符串)。

1. 解决方案:括号

在字符串周围加上括号,您甚至可以将它们连接起来,而无需在它们之间使用+符号:

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

很高兴知道:如果一行中没有变量,则该行不需要前导f

高兴知道:您可以在每行末尾使用反斜杠 ( \\ ) 存档相同的结果,而不是用括号括起来,但因此,对于PEP8,您应该更喜欢用括号来继续行:

通过将表达式括在括号中,可以将长行分成多行。 这些应该优先于使用反斜杠进行行延续。

2. 解决方案:多行字符串

在多行字符串中,您不需要显式插入\\n ,Python 会为您处理:

a_str = f"""This is a line
        {str1}
        This is line 2
        {str2}
        This is line 3"""

很高兴知道:只要确保正确对齐代码,否则每行前面都会有前导空格。


顺便说一句:你不应该调用你的变量str因为那是数据类型本身的名称。

格式化字符串的来源:

我会添加我需要连接到列表的所有内容,然后在换行符处加入它。

my_str = '\n'.join(['string1', variable1, 'string2', variable2])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM