我有一长串代码,我希望在多行之间分解.我使用什么,语法是什么?
例如,添加一串字符串,
e = 'a' + 'b' + 'c' + 'd'
Run Code Online (Sandbox Code Playgroud)
并将它分成两行:
e = 'a' + 'b' +
'c' + 'd'
Run Code Online (Sandbox Code Playgroud) 在python 2.6中,为什么以下行有效?
my_line = 'foo' 'bar'
Run Code Online (Sandbox Code Playgroud)
如果这是有效的,为什么不是以下内容:
my_list = 1 2
Run Code Online (Sandbox Code Playgroud)
第一个例子是字符串连接,但是,以下内容也无效(感谢上帝):
foo = 'foo'
bar = 'bar'
foo_bar = foo bar
Run Code Online (Sandbox Code Playgroud) 我有这行代码:
assert 0 <= j <= self.n, "First edge needs to be between 0 and {}".format(self.n)
Run Code Online (Sandbox Code Playgroud)
我希望pep8很开心,但我不明白如何打破这条线.我试着用逗号破解并得到无效的语法.我已经尝试用额外的"" 来打破字符串,如如何打破PEP8合规性的长串线?.PEP8很高兴,但断言只产生了消息的前半部分.
打破长断言字符串的正确方法是什么?
什么是在程序中编写单行但长字符串的Pythonic方法:
s = 'This is a long long string.'
Run Code Online (Sandbox Code Playgroud)
此外,字符串可能需要使用变量格式化:
s = 'This is a {} long long string.'.format('formatted')
Run Code Online (Sandbox Code Playgroud)
s = 'This is a long '\
'long '\
'string.'
Run Code Online (Sandbox Code Playgroud)
额外的尾随\
字符使重新格式化变得非常困难.用a连接两行\
会出错.
s = 'This is a long \
long \
string.'
Run Code Online (Sandbox Code Playgroud)
除了上面的类似问题之外,后续行必须在最开始时对齐,这在第一行缩进时给出了难以理解的可读性.