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

时间:2015-12-15 17:41:03

标签: python string concatenation

我有一些字符串要连接,结果字符串会很长。我也有一些变量要连接起来。

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

以下代码引发错误。

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

请建议一种方法。

4 个答案:

答案 0 :(得分:40)

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

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

答案 1 :(得分:9)

Python不是php,您无需将$放在变量名之前。

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

答案 2 :(得分:2)

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,因为那是数据类型本身的名称。

格式化字符串的来源:

答案 3 :(得分:1)

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

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