How can I break up this long line in Python?
如何设置这样的长行格式?我想让它的宽度不超过80个字符:
1 | logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title)) |
这是我最好的选择吗?
1 2 | url ="Skipping {0} because its thumbnail was already in our system as {1}." logger.info(url.format(line[indexes['url']], video.title)) |
这是一个开始。在使用它们的代码之外定义更长的字符串并不是一个坏习惯。这是一种分离数据和行为的方法。第一种选择是通过使字符串文本彼此相邻来将它们隐式地连接在一起:
1 2 | ("This is the first line of my text," "which will be joined to a second.") |
或者在行尾延续的情况下,这种延续有点脆弱,因为这是可行的:
1 2 | "This is the first line of my text," \ "which will be joined to a second." |
但这并不是:
1 2 | "This is the first line of my text," \ "which will be joined to a second." |
看到区别了吗?不?当这是你的代码时,你也不会。
隐式连接的缺点是它只与字符串文本一起使用,而不与取自变量,这样重构时事情会变得更加复杂。此外,只能对组合字符串整体插入格式。
或者,可以使用串联运算符(
1 2 | ("This is the first line of my text," + "which will be joined to a second.") |
正如python的禅所说,显式优于隐式,但是这会创建三个字符串而不是一个字符串,并且使用的内存是写的两个字符串的两倍:加上一个字符串,这两个字符串连接在一起,所以您必须知道何时忽略禅。好处是您可以将格式应用于每一行单独的子字符串,或从括号外到整批的子字符串。
最后,您可以使用三重引号字符串:
1 2 | """This is the first line of my text which will be joined to a second.""" |
这通常是我的最爱,尽管它的行为与换行稍有不同,并且在随后的行中任何前导空格都将显示在最后的字符串中。可以用转义反斜杠消除换行符。
1 2 | """This is the first line of my text \ which will be joined to a second.""" |
这与上面的相同技术有相同的问题,因为正确的代码与不正确的代码之间只有不可见的空白。
哪一个是"最好的"取决于你的特殊情况,但答案不仅仅是审美上的,而是一种微妙的不同行为。
连续的字符串文本由编译器联接,带括号的表达式被认为是一行代码:
1 2 3 | logger.info("Skipping {0} because it's thumbnail was" "already in our system as {1}.".format(line[indexes['url']], video.title)) |
就我个人而言,我不喜欢挂开放块,所以我将其格式化为:
1 2 3 4 | logger.info( 'Skipping {0} because its thumbnail was already in our system as {1}.' .format(line[indexes['url']], video.title) ) |
一般来说,我不会费太大的力气使代码完全适合80列的行。这是值得保持线长度合理的水平,但硬80限制是过去的事情。
可以使用textwarp模块将其拆分为多行
1 2 3 4 | import textwrap str="ABCDEFGHIJKLIMNO" print(" ".join(textwrap.wrap(str,8))) |
ABCDEFGH
IJKLIMNO
从文档中:
textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.Optional keyword arguments correspond to the instance attributes of
TextWrapper , documented below. width defaults to70 .See the
TextWrapper.wrap() method for additional details on how wrap() behaves.