gpt4 book ai didi

python - 使长字符串换行的好方法?

转载 作者:IT老高 更新时间:2023-10-28 22:01:57 25 4
gpt4 key购买 nike

在我的项目中,我有一堆从文件中读取的字符串。其中大多数在命令控制台中打印时,长度超过 80 个字符并环绕,看起来很难看。

我希望能够让 Python 读取字符串,然后测试它的长度是否超过 75 个字符。如果是,则将字符串拆分为多个字符串,然后在新行上一个接一个地打印。我也希望它很聪明,而不是切断完整的单词。即"The quick brown <newline> fox..."而不是 "the quick bro<newline>wn fox..." .

我尝试修改类似的代码,在设定长度后截断字符串,但只是将字符串丢弃而不是将其放在新行中。

我可以使用哪些方法来完成此任务?

最佳答案

您可以使用 textwrap模块:

>>> import textwrap
>>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
>>> print(textwrap.fill(strs, 20))
In my project, I
have a bunch of
strings that are
read in from a file.
Most of them, when
printed in the
command console,
exceed 80 characters
in length and wrap
around, looking
ugly.

帮助 textwrap.fill :

>>> textwrap.fill?

Definition: textwrap.fill(text, width=70, **kwargs)
Docstring:
Fill a single paragraph of text, returning a new string.

Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.

如果您不想将一行合并到另一行,请使用 regex:

import re


strs = """In my project, I have a bunch of strings that are.
Read in from a file.
Most of them, when printed in the command console, exceed 80.
Characters in length and wrap around, looking ugly."""

print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs)))

# Reading a single line at once:
for x in strs.splitlines():
print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))

输出:

In my project, I have a bunch of strings
that are.
Read in from a file.
Most of them, when printed in the
command console, exceed 80.
Characters in length and wrap around,
looking ugly.

关于python - 使长字符串换行的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16430200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com