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

新手上路,请多包涵

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

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

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

我可以使用哪些方法来完成此操作?

原文由 Joshua Merriman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 413
2 个回答

您可以使用 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.

原文由 Ashwini Chaudhary 发布,翻译遵循 CC BY-SA 3.0 许可协议

这就是 textwrap 模块的用途。尝试 textwrap.fill(some_string, width=75)

原文由 jwodder 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题