Python风格的字符串行延续?

2024-04-26 20:41:45 发布

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

为了遵守python风格的规则,我将编辑器设置为最多79个cols。

在PEP中,它建议在括号、圆括号和大括号中使用python的隐式延续。然而,当处理字符串时,当我达到col限制时,它会变得有点奇怪。

例如,尝试使用多行

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

所以,我的问题是——有些人对如何做到这一点有什么建议,而我在风格指南中是否遗漏了一些东西来说明我应该如何做到这一点?

谢谢。


Tags: andhello风格moresomepeoplestackoverflowdo
3条回答

另一种可能是使用textwrap模块。这也避免了问题中提到的“字符串只是坐在一个不知名的地方”的问题。

import textwrap
mystr = """\
        Why, hello there
        wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))

由于adjacent string literals are automatically joint into a single string,您只需按照PEP 8的建议在括号内使用隐含的行继续:

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

只是指出是括号的使用调用了自动连接。如果你碰巧已经在声明中使用了它们,那就没问题了。否则,我只使用“\”而不是插入括号(这是大多数ide自动为您做的事情)。缩进应该对齐字符串的连续部分,因此符合PEP8。E、 g.:

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

相关问题 更多 >