正如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.")
使用黑色[https://github.com/psf/black],我像这样格式化它。
help=f"""filters, lista de filtros para cargar las base de conocimiento.
Pueden mandarse solo algunos filtros ya que no son obligatorios,
por ejemplo, si no se manda sts, se cargarán todos las bases de todos los estados.""",
我以前用过textwrap.dedent。这有点麻烦,所以我现在更喜欢行延续,但如果你真的想要块缩进,我认为这很好。
示例代码(其中trim是去掉带有切片的第一个'\n'):
import textwrap as tw
x = """\
This is a yet another test.
This is only a test"""
print(tw.dedent(x))
解释:
Dedent根据新行前第一行文本中的空白计算缩进。如果你想调整它,你可以使用re模块轻松地重新实现它。
这种方法有局限性,很长的行可能仍然比你想要的长,在这种情况下,其他方法连接字符串更适合。