Python 风格 - 字符串的续行?

182 投票
5 回答
148660 浏览
提问于 2025-04-16 14:26

我在尝试遵循Python的风格规则时,把我的编辑器设置为最大79列。

在PEP(Python增强提案)中,建议在括号、圆括号和大括号中使用Python的隐式续行。不过,当处理字符串并且达到列限制时,就有点奇怪了。

比如,尝试使用多行字符串:

mystr = """Why, hello there
wonderful stackoverflow people!"""

会返回:

"Why, hello there\nwonderful stackoverflow people!"

这样是可以的:

mystr = "Why, hello there \
wonderful stackoverflow people!"

因为它返回的是:

"Why, hello there wonderful stackoverflow people!"

但是,当语句缩进几层时,这看起来就有点奇怪:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
wonderful stackoverflow people!"

如果你尝试缩进第二行:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
            wonderful stackoverflow people!"

你的字符串最后变成了:

"Why, hello there                wonderful stackoverflow people!"

我找到的唯一解决办法是:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there" \
            "wonderful stackoverflow people!"

我更喜欢这种方式,但看起来也有点不舒服,因为它就像一个字符串孤零零地放在中间。这会产生正确的:

"Why, hello there wonderful stackoverflow people!"

所以,我的问题是——大家有什么建议来处理这个问题?我是不是在风格指南中漏掉了什么,应该怎么做呢?

谢谢。

5 个回答

6

这是一种相当简单明了的方法:

myStr = ("firstPartOfMyString"+
         "secondPartOfMyString"+
         "thirdPartOfMyString")
54

我想强调一下,使用括号会自动连接字符串。如果你在语句中已经用了括号,那这样做没问题。否则,我建议直接用反斜杠(\)来连接字符串,而不是插入括号(大多数开发工具会自动为你加上括号)。另外,缩进应该对齐,这样才能符合PEP8的规范。例如:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"
281

因为相邻的字符串字面量会自动连接成一个单一的字符串,所以你可以在括号内使用隐含的换行,这样做是符合PEP 8的建议:

print("Why, hello there wonderful "
      "stackoverflow people!")

撰写回答