正如PEP8所建议的那样,在python程序中保持低于80列的规则,对于长字符串,我怎么能遵守这个规则呢?

s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."

我该如何把它扩展到下面一行呢?

s = "this is my really, really, really, really, really, really" + 
    "really long string that I'd like to shorten."

当前回答

隐式连接可能是最干净的解决方案:

s = "this is my really, really, really, really, really, really," \
    " really long string that I'd like to shorten."

编辑经过反思,我同意托德的建议,使用括号而不是行接续更好,因为他给出了所有的理由。我唯一的犹豫是,用括号括起来的字符串和元组比较容易混淆。

其他回答

隐式连接可能是最干净的解决方案:

s = "this is my really, really, really, really, really, really," \
    " really long string that I'd like to shorten."

编辑经过反思,我同意托德的建议,使用括号而不是行接续更好,因为他给出了所有的理由。我唯一的犹豫是,用括号括起来的字符串和元组比较容易混淆。

我以前用过textwrap.dedent。这有点麻烦,所以我现在更喜欢行延续,但如果你真的想要块缩进,我认为这很好。

示例代码(其中trim是去掉带有切片的第一个'\n'):

import textwrap as tw
x = """\
       This is a yet another test.
       This is only a test"""
print(tw.dedent(x))

解释:

Dedent根据新行前第一行文本中的空白计算缩进。如果你想调整它,你可以使用re模块轻松地重新实现它。

这种方法有局限性,很长的行可能仍然比你想要的长,在这种情况下,其他方法连接字符串更适合。

我觉得你问题中最重要的一个词是“suggest”。

编码标准是很有趣的东西。通常他们提供的指导在编写时有很好的基础(例如,大多数终端无法在一行上显示> 80个字符),但随着时间的推移,它们在功能上变得过时了,但仍然被严格遵守。我猜您在这里需要做的是权衡“破坏”特定建议与代码的可读性和可维护性之间的相对优点。

抱歉,这并不能直接回答你的问题。

您丢失了一个空格,您可能需要一个行延续字符,即。一个\。

s = "this is my really, really, really, really, really, really" +  \
    " really long string that I'd like to shorten."

甚至:

s = "this is my really, really, really, really, really, really"  \
    " really long string that I'd like to shorten."

parns也可以代替行续符,但可能会有人认为您打算使用元组,而只是忘记了逗号。举个例子:

s = ("this is my really, really, really, really, really, really"
    " really long string that I'd like to shorten.")

对比:

s = ("this is my really, really, really, really, really, really",
    " really long string that I'd like to shorten.")

使用Python的动态类型,代码可以以任何一种方式运行,但会产生不正确的结果。

使用\你可以将语句扩展到多行:

s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."

应该工作。