用多行连接python中的字符串

2024-05-03 06:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

下面的代码抛出错误。

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

请建议一种方法。


Tags: 方法字符串代码is错误linethis建议
3条回答

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解决方案

从Python 3.6开始,您可以使用所谓的“格式化字符串”(或“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"
         "This is line 3") # no variable here, so no leading f

很好地知道:如果行中没有变量,则不需要该行的前导f

很高兴知道:您可以在每一行的末尾用反斜杠(\)来存档相同的结果,而不是用圆括号括起来,但是相应地,PEP8您应该更喜欢用圆括号来换行:

Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

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

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

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

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


顺便说一下:您不应该调用变量str,因为这是数据类型本身的名称。

格式化字符串的源:

相关问题 更多 >