正如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, " # comments ok
"really long string that I'd like to shorten.")
我使用谷歌搜索“python行长”,它返回PEP8链接作为第一个结果,但也链接到另一个关于这个主题的StackOverflow帖子:“为什么python PEP-8应该指定79个字符的最大行长?”
另一个好的搜索短语是“python line continuation”。
反斜杠:
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.")