如何编写符合PEP8的非常长的string,防止E501

由于PEP8build议保持低于你的Python程序的80列规则,我怎么能遵守与长string,即

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

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

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

编辑在反思我同意,托德的build议,使用括号,而不是连续续行更好的所有原因,他给。 我唯一的犹豫是,把元组与括号内的string混淆是相对容易的。

另外,因为相邻的string常量是自动连接的,所以你可以这样编码:

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

请注意没有加号,并且在示例的格式之后添加了额外的逗号和空格。

就我个人而言,我不喜欢反斜杠,我记得在某个地方读到它的使用实际上已经被弃用,而更倾向于这种更明确的forms。 记住“显式比隐式更好”。

我认为反斜杠不那么清楚,不太有用,因为这实际上是逃避了换行符。 如果有必要的话,就不可能在行结束后加上注释。 可以用串联的string常量来做到这一点:

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

我使用了一个“python line length”的Googlesearch作为第一个结果返回PEP8链接,但是也链接到了另一个关于这个主题的好的StackOverflow文章:“ 为什么Python PEP-8指定最大行长度为79个字符?

另一个好的search短语是“python line continuation”。

我认为你的问题中最重要的词是“build议”。

编码标准是有趣的事情。 通常他们提供的指导在撰写时(例如,大多数terminal不能显示大于80个字符的行)具有非常好的基础,但是随着时间的推移,它们在function上已经过时,但仍然严格遵守。 我想你在这里需要做的是衡量“打破”你的代码的可读性和可抑制性的特定build议的相对优点。

对不起,这不直接回答你的问题。

你失去了一个空间,你可能需要一个续行字符,即。 一个\

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

Parens也会工作,而不是延续线路,但是你冒着有人认为你打算拥有一个元组而忘记了一个逗号。 举个例子:

 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的dynamictypes,代码可能会以任何方式运行,但会产生不正确的结果。

反斜杠:

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

或包裹在parens:

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

应该pipe用。