正如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."
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."
或者用括号括起来:
s = ("this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten.")
可用的选项:
反斜杠:"foo" \ "bar"
"foo" + " \ "bar"
括号:
(“foo”“酒吧”)
带加号的括号:("foo" + "bar")
PEP8, E502:括号之间的反斜杠是多余的
避免
避免使用逗号:("foo", "bar")来定义一个元组。
>>> s = "a" \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = "a" + \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = ("a"
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>> s = ("a",
... "b")
>>> type(s)
<class 'tuple'>
>>> s = ("a" +
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>>