我如何用Python来打破这条长长的线?

时间:2022-02-14 07:50:12

How would you go about formatting a long line such as this? I'd like to get it to no more than 80 characters wide:

你会如何对这样的一行进行格式化呢?我想把它扩展到不超过80个字符:

logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title))

Is this my best option?

这是我最好的选择吗?

url = "Skipping {0} because its thumbnail was already in our system as {1}."
logger.info(url.format(line[indexes['url']], video.title))

4 个解决方案

#1


237  

That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

这是一个开始。在使用字符串的代码之外定义较长的字符串并不是一个坏的做法。这是一种分离数据和行为的方法。您的第一个选项是通过将字符串连接在一起,从而隐式地连接字符串:

("This is the first line of my text, "
"which will be joined to a second.")

Or with line ending continuations, which is a little more fragile, as this works:

或者用直线结束延续,这是比较脆弱的,

"This is the first line of my text, " \
"which will be joined to a second."

But this doesn't:

但这并不是:

"This is the first line of my text, " \ 
"which will be joined to a second."

See the difference? No? Well you won't when it's your code either.

看出不同了吗?没有?当它是你的代码时,你也不会。

The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

隐式连接的缺点是它只适用于字符串字面量,而不适用于从变量中提取的字符串,因此当您重构时,事情会变得更加复杂。而且,您只能在合并的字符串上插入格式。

Alternatively, you can join explicitly using the concatenation operator (+):

或者,您可以使用连接操作符(+)显式连接:

("This is the first line of my text, " + 
"which will be joined to a second.")

Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

显式优于隐式,python的禅说,但是这将创建三个字符串而不是一个,并使用两倍内存:有两个你所写,+ 1这是他们两个连在一起的,所以你必须知道何时忽略禅。好处是,您可以对每一行上的任何子字符串分别应用格式,或者从圆括号外对整个部分应用格式。

Finally, you can use triple-quoted strings:

最后,可以使用三引号的字符串:

"""This is the first line of my text
which will be joined to a second."""

This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

这通常是我最喜欢的,尽管它的行为稍有不同,因为换行符和后续行的任何领先空格都将显示在最后的字符串中。您可以使用转义反斜杠消除换行。

"""This is the first line of my text \
which will be joined to a second."""

This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

这与上面的相同技术有相同的问题,因为正确的代码与不正确的代码只有看不见的空格。

Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

哪个是“最好的”取决于你的具体情况,但答案不仅仅是审美,而是一种微妙不同的行为。

#2


28  

Consecutive string literals are joined by the compiler, and parenthesized expressions are considered to be a single line of code:

连续的字符串文字由编译器连接,圆括号表达式被认为是一行代码:

logger.info("Skipping {0} because it's thumbnail was "
  "already in our system as {1}.".format(line[indexes['url']],
  video.title))

#3


8  

Personally I dislike hanging open blocks, so I'd format it as:

就我个人而言,我不喜欢悬挂的方块,所以我会把它格式化为:

logger.info(
    'Skipping {0} because its thumbnail was already in our system as {1}.'
    .format(line[indexes['url']], video.title)
)

In general I wouldn't bother struggle too hard to make code fit exactly within a 80-column line. It's worth keeping line length down to reasonable levels, but the hard 80 limit is a thing of the past.

一般来说,我不会花太大的力气让代码正好适合80列行。将线路长度保持在合理的水平上是值得的,但是硬80限制已经成为过去。

#4


0  

You can use textwrap module to break it in multiple lines

可以使用textwrap模块将其拆分为多行

import textwrap
str="ABCDEFGHIJKLIMNO"
print("\n".join(textwrap.wrap(str,8)))

ABCDEFGH
IJKLIMNO

ABCDEFGH IJKLIMNO

Documentation for it here https://docs.python.org/2/library/textwrap.html
textwrap.fill(text[, width[, ...]])
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for

它的文档,https://docs.python.org/2/library/textwrap.html textwrap。填充(文本[,宽度[,…]))将单个段落封装在文本中,并返回包含被包装段落的单个字符串。填满()的简称

"\n".join(wrap(text, ...)) wrap or fill can be used

“\ n”。可以使用join(wrap)或wrap(fill)

#1


237  

That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

这是一个开始。在使用字符串的代码之外定义较长的字符串并不是一个坏的做法。这是一种分离数据和行为的方法。您的第一个选项是通过将字符串连接在一起,从而隐式地连接字符串:

("This is the first line of my text, "
"which will be joined to a second.")

Or with line ending continuations, which is a little more fragile, as this works:

或者用直线结束延续,这是比较脆弱的,

"This is the first line of my text, " \
"which will be joined to a second."

But this doesn't:

但这并不是:

"This is the first line of my text, " \ 
"which will be joined to a second."

See the difference? No? Well you won't when it's your code either.

看出不同了吗?没有?当它是你的代码时,你也不会。

The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

隐式连接的缺点是它只适用于字符串字面量,而不适用于从变量中提取的字符串,因此当您重构时,事情会变得更加复杂。而且,您只能在合并的字符串上插入格式。

Alternatively, you can join explicitly using the concatenation operator (+):

或者,您可以使用连接操作符(+)显式连接:

("This is the first line of my text, " + 
"which will be joined to a second.")

Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

显式优于隐式,python的禅说,但是这将创建三个字符串而不是一个,并使用两倍内存:有两个你所写,+ 1这是他们两个连在一起的,所以你必须知道何时忽略禅。好处是,您可以对每一行上的任何子字符串分别应用格式,或者从圆括号外对整个部分应用格式。

Finally, you can use triple-quoted strings:

最后,可以使用三引号的字符串:

"""This is the first line of my text
which will be joined to a second."""

This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

这通常是我最喜欢的,尽管它的行为稍有不同,因为换行符和后续行的任何领先空格都将显示在最后的字符串中。您可以使用转义反斜杠消除换行。

"""This is the first line of my text \
which will be joined to a second."""

This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

这与上面的相同技术有相同的问题,因为正确的代码与不正确的代码只有看不见的空格。

Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

哪个是“最好的”取决于你的具体情况,但答案不仅仅是审美,而是一种微妙不同的行为。

#2


28  

Consecutive string literals are joined by the compiler, and parenthesized expressions are considered to be a single line of code:

连续的字符串文字由编译器连接,圆括号表达式被认为是一行代码:

logger.info("Skipping {0} because it's thumbnail was "
  "already in our system as {1}.".format(line[indexes['url']],
  video.title))

#3


8  

Personally I dislike hanging open blocks, so I'd format it as:

就我个人而言,我不喜欢悬挂的方块,所以我会把它格式化为:

logger.info(
    'Skipping {0} because its thumbnail was already in our system as {1}.'
    .format(line[indexes['url']], video.title)
)

In general I wouldn't bother struggle too hard to make code fit exactly within a 80-column line. It's worth keeping line length down to reasonable levels, but the hard 80 limit is a thing of the past.

一般来说,我不会花太大的力气让代码正好适合80列行。将线路长度保持在合理的水平上是值得的,但是硬80限制已经成为过去。

#4


0  

You can use textwrap module to break it in multiple lines

可以使用textwrap模块将其拆分为多行

import textwrap
str="ABCDEFGHIJKLIMNO"
print("\n".join(textwrap.wrap(str,8)))

ABCDEFGH
IJKLIMNO

ABCDEFGH IJKLIMNO

Documentation for it here https://docs.python.org/2/library/textwrap.html
textwrap.fill(text[, width[, ...]])
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for

它的文档,https://docs.python.org/2/library/textwrap.html textwrap。填充(文本[,宽度[,…]))将单个段落封装在文本中,并返回包含被包装段落的单个字符串。填满()的简称

"\n".join(wrap(text, ...)) wrap or fill can be used

“\ n”。可以使用join(wrap)或wrap(fill)