我怎样才能在Python中分解这么长的一行呢?

发布于 2024-08-17 17:30:53 字数 370 浏览 2 评论 0原文

您将如何格式化这样的长行?我希望其宽度不超过 80 个字符:

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

这是我的最佳选择吗?

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

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:

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))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

伤感在游骋 2024-08-24 17:30:53

这是一个开始。在使用较长字符串的代码之外定义它们并不是一个坏习惯。这是一种分离数据和行为的方法。您的第一个选择是通过使字符串文字彼此相邻来隐式地将它们连接在一起:

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

或者使用行结尾延续,这有点脆弱,因为这是有效的:

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

但这不行:

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

看到区别了吗?不?好吧,当它是你的代码时你也不会。

(在第二个示例中,\ 之后有一个空格。)

隐式连接的缺点是它仅适用于字符串文字,不适用于从
变量,因此当您重构时事情可能会变得更加棘手。此外,您只能对整个组合字符串进行插值格式。

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

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

正如 Python 的禅宗所说,显式优于隐式,但这会创建三个字符串而不是一个,并且使用两倍的内存:有你写的两个,再加上两个结合在一起的一个,所以你必须知道什么时候忽略禅宗。好处是您可以应用格式
每行上单独的任何子字符串,或从括号外到整个字符串。

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

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

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

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

这与上面的相同技术具有相同的问题,因为正确的代码与错误的代码仅通过不可见的空格不同。

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

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.

(There's a space after \ in the second example.)

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.

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.

左耳近心 2024-08-24 17:30:53

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

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

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))
草莓酥 2024-08-24 17:30:53

就我个人而言,我不喜欢悬挂开放块,因此我将其格式设置为:

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

一般来说,我不会费力去使代码完全适合 80 列行。将行长度保持在合理的水平是值得的,但 80 的硬性限制已成为过去。

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.

青柠芒果 2024-08-24 17:30:53

您可以使用 textwrap 模块将其分成多行

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

ABCDEFGH
IJKLIMNO

来自 文档

textwrap.wrap(text[, width[, ...]])
将单个段落包装在文本(字符串)中,因此每行的长度最多为 width 个字符。返回输出行列表,没有最终换行符。

可选关键字参数对应于 TextWrapper< 的实例属性/code>,记录如下。宽度默认为70

请参阅TextWrapper.wrap()方法,了解有关 wrap() 行为的更多详细信息。


You can use textwrap module to break it in multiple lines

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

ABCDEFGH
IJKLIMNO

From the documentation:

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 to 70.

See the TextWrapper.wrap() method for additional details on how wrap() behaves.

骄兵必败 2024-08-24 17:30:53

对于那些也尝试在长字符串上调用 .format() 的人,并且无法在不破坏后续 .format( 的情况下使用一些最流行的字符串包装技术> 调用时,您可以执行 str.format("", 1, 2) 而不是 "".format(1, 2) 这可以让您用以下命令来中断字符串。无论你喜欢什么技术,例如:

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

可以

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

否则,唯一的可能性是使用行结束延续,我个人不喜欢。

For anyone who is also trying to call .format() on a long string, and is unable to use some of the most popular string wrapping techniques without breaking the subsequent .format( call, you can do str.format("", 1, 2) instead of "".format(1, 2). This lets you break the string with whatever technique you like. For example:

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

can be

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

Otherwise, the only possibility is using line ending continuations, which I personally am not a fan of.

浅忆流年 2024-08-24 17:30:53

无需额外加载包的解决方案:

def split_by_len(txt: str, l: int, sep: str or None='\n') -> str or list:
    """
    txt: str text
    l: split length (symbols per split)
    sep: separate string or None for list of strs
    """
    spl_list = [txt[i * l : i * l + l] for i in range(len(txt) // l + 1)]
    return spl_list if sep==None else sep.join(spl_list)

示例 1:

print(split_by_len(txt='XXXXX', l=2, sep='\n'))

XX
XX
X

示例 2:

print(split_by_len(txt='XXXXX', l=2, sep=' '))

XX XX X

示例 3:

print(split_by_len(txt='XXXXX', l=2, sep=None))

['XX', 'XX', 'X']

Solution without extra packages load:

def split_by_len(txt: str, l: int, sep: str or None='\n') -> str or list:
    """
    txt: str text
    l: split length (symbols per split)
    sep: separate string or None for list of strs
    """
    spl_list = [txt[i * l : i * l + l] for i in range(len(txt) // l + 1)]
    return spl_list if sep==None else sep.join(spl_list)

Example 1:

print(split_by_len(txt='XXXXX', l=2, sep='\n'))

XX
XX
X

Example 2:

print(split_by_len(txt='XXXXX', l=2, sep=' '))

XX XX X

Example 3:

print(split_by_len(txt='XXXXX', l=2, sep=None))

['XX', 'XX', 'X']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文