Python样式 - 用字符串继续行?

sjm*_*jmh 148 python coding-style

在尝试遵守python样式规则时,我将编辑器设置为最多79列.

在PEP中,它建议在括号,括号和括号内使用python隐含的延续.但是,当我达到col限制时处理字符串时,它会有点奇怪.

例如,尝试使用多行

mystr = """Why, hello there
wonderful stackoverflow people!"""
Run Code Online (Sandbox Code Playgroud)

将返回

"Why, hello there\nwonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)

这有效:

mystr = "Why, hello there \
wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)

因为它返回:

"Why, hello there wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)

但是,当语句缩进几个块时,这看起来很奇怪:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)

如果您尝试缩进第二行:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
            wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)

你的字符串最终为:

"Why, hello there                wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)

我发现解决这个问题的唯一方法是:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there" \
            "wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)

我觉得哪个更好,但眼睛也有些不安,因为看起来有一根绳子只是坐在不知名的地方.这将产生适当的:

"Why, hello there wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是 - 关于如何做到这一点的一些人的建议是什么?在样式指南中是否有我缺少的东西,它确实显示了我应该如何做到这一点?

谢谢.

Sve*_*ach 229

由于相邻的字符串文字会自动连接成一个字符串,因此您可以按照PEP 8的建议使用括号内的隐含的行继续:

print("Why, hello there wonderful "
      "stackoverflow people!")
Run Code Online (Sandbox Code Playgroud)

  • 谢谢斯文,我比我使用的风格更喜欢这个。 (2认同)
  • 我认为这只是一个技巧,但在阅读了 python 文档后,我必须说,这很整洁。谢谢 ! (2认同)

小智 44

只是指出它是使用括号来调用自动连接.如果您碰巧已经在声明中使用它们,那就没关系了.否则,我只会使用'\'而不是插入括号(这是大多数IDE自动为您执行的操作).缩进应该对齐字符串continuation,因此它符合PEP8.例如:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"
Run Code Online (Sandbox Code Playgroud)


小智 6

这是一个非常干净的方法:

myStr = ("firstPartOfMyString"+
         "secondPartOfMyString"+
         "thirdPartOfMyString")
Run Code Online (Sandbox Code Playgroud)


Ali*_*liA 5

另一种可能性是使用textwrap模块。这也避免了问题中提到的“字符串只是坐在虚无之中”的问题。

import textwrap
mystr = """\
        Why, hello there
        wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))
Run Code Online (Sandbox Code Playgroud)