我有这行代码:
assert 0 <= j <= self.n, "First edge needs to be between 0 and {}".format(self.n)
我希望pep8很开心,但我不明白如何打破这条线。我试着用逗号破解并得到无效的语法。我已经尝试用How to break long string lines for PEP8 compliance?中的附加“”来破坏字符串。 PEP8很高兴,但断言只产生了消息的前半部分。
打破长断言字符串的正确方法是什么?
答案 0 :(得分:7)
使用parens:
assert 0 <= j <= self.n, ("First edge needs to be "
"between 0 and {}".format(self.n))
或者:
assert 0 <= j <= self.n, ("First edge needs to be between 0 and {}"
.format(self.n))
或使用format
函数的parens:
assert 0 <= j <= self.n, "First edge needs to be between 0 and {}".format(
self.n)
答案 1 :(得分:4)
当您使用ReadFileAndStoreInArrayList(file);
选项运行解释器时,可以优化考虑assert
语句,您可能希望将它保留为单个语句并在括号中使用字符串连接:
-O
或在Python 3.6 +中使用f-strings:
assert 0 <= j <= self.n, ('First edge needs to be between '
'0 and {}'.format(self.n))
如果您不关心优化(例如您正在编写测试),那么将该行分为两个语句也是一个选项:
assert 0 <= j <= self.n, ('First edge needs to be between '
f'0 and {self.n}')
答案 2 :(得分:2)
您可以强行打破这样的新行:
assert 0 <= j <= self.n,\
"print stuff"
如果括号等没有自动执行,那总是会使行继续。你可以将下一行缩进到最可读的位置,就像我上面所做的那样。