Dev*_*rre 58
我的当前编辑器(Kate)已配置为在行长度达到或超过80个字符时在字边界上引入换行符.这使我很明显我超越了界限.此外,还有一条标有80个字符位置的红线,让我提前警告线路何时会流过.这些让我计划适合多条物理线路的逻辑线路.
至于如何实际适合它们,有几种机制.您可以使用\结束该行,但这很容易出错.
# works
print 4 + \
2
# doesn't work
print 4 + \
2
Run Code Online (Sandbox Code Playgroud)
区别?区别是不可见的 - 在第二种情况下反斜杠之后有一个空白字符.哎呀!
应该做什么呢?好吧,用括号括起来.
print (4 +
2)
Run Code Online (Sandbox Code Playgroud)
不需要.这实际上普遍适用,你永远不会需要\.即使是属性访问边界!
print (foo
.bar())
Run Code Online (Sandbox Code Playgroud)
对于字符串,您可以显式添加它们,也可以使用C风格连接隐式添加它们.
# all of these do exactly the same thing
print ("123"
"456")
print ("123" +
"456")
print "123456"
Run Code Online (Sandbox Code Playgroud)
最后,任何形式的括号((),[].{}),而不仅仅是括号,都可以在任何地方放置换行符.因此,例如,只要元素用逗号分隔,就可以在多行上使用列表文字.
所有这些以及更多内容都可以在Python 的官方文档中找到.另外,快速记录,PEP-8指定79个字符作为限制,而不是80--如果你有80个字符,你已经超过了它.
Tor*_*amo 22
如果超过80个字符的代码是函数调用(或定义),则断开参数行.Python将识别括号,并将其视为一行.
function(arg, arg, arg, arg,
arg, arg, arg...)
Run Code Online (Sandbox Code Playgroud)
如果超过80个字符的代码是一行不易破解的代码,则可以使用反斜杠\"转义"换行符.
some.weird.namespace.thing.that.is.long = ','.join(strings) + \
'another string'
Run Code Online (Sandbox Code Playgroud)
您也可以使用括号来获得优势.
some.weird.namespace.thing.that.is.long = (','.join(strings) +
'another string')
Run Code Online (Sandbox Code Playgroud)
所有类型的set括号{}(dict/set),[](list),()(元组)都可以跨越几行而没有问题.这样可以实现更好的格式化.
mydict = {
'key': 'value',
'yes': 'no'
}
Run Code Online (Sandbox Code Playgroud)
Kim*_*ais 18
惯用Python说:
使用反斜杠作为最后的手段
因此,如果可以使用括号(),请避免使用反斜杠.如果你有a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines.across.the.whole.trainyard.and.several.states()这样的事情:
lines = a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines
lines.across.the.whole.trainyard.and.several.states()
Run Code Online (Sandbox Code Playgroud)
或者,最好重构您的代码.请.
Eri*_*got 18
我会在之前的答案中加两点:
字符串可以自动连接,非常方便:
this_is_a_long_string = ("lkjlkj lkj lkj mlkj mlkj mlkj mlkj mlkj mlkj "
"rest of the string: no string addition is necessary!"
" You can do it many times!")
Run Code Online (Sandbox Code Playgroud)
注意,这是有效的:这并不会导致运行该代码时计算的字符串连接:不是,这是直接认为是一个长字符串常量,因此它是有效的.
与Devin的回答有关的一点警告:"括号"语法实际上并不"普遍地起作用".例如,d [42] ="H22G"不能写为
(d
[42] = "H2G2")
Run Code Online (Sandbox Code Playgroud)
因为括号只能在"计算"表达式周围使用(这不包括如上所述的赋值(=)).
另一个示例是以下代码,它会生成语法错误:
with (open("..... very long file name .....")
as input_file):
Run Code Online (Sandbox Code Playgroud)
实际上,括号不能放在语句中,更一般地说(只有表达式).
在这些情况下,可以使用"\"语法,或者更好(因为如果可能,应避免使用"\"),将代码拆分为多个语句.