问题
我们有一些很长的字符串,想将它们重新格式化,使得它们能按照用户指定的列数来显示。
解决方案
可以使用 textwrap 模块来重新格式化文本的输出。例如,假设有如下这段长字符串:
s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
the eyes, not around the eyes, don't look around the eyes, \
look into my eyes, you're under."
这里可以用 textwrap 模块以多种方式来重新格式化字符串:
s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
the eyes, not around the eyes, don't look around the eyes, \
look into my eyes, you're under."
print(s)
print()
import textwrap
print(textwrap.fill(s,70))
print()
print(textwrap.fill(s,40))
print()
print(textwrap.fill(s,40,initial_indent=' '))
print()
print(textwrap.fill(s,40,subsequent_indent=' '))
输出:
Look into my eyes, look into my eyes, the eyes, the eyes, the eyes, not around the eyes, don't look around the eyes, look into my eyes, you're under.
Look into my eyes, look into my eyes, the eyes, the eyes, the eyes,
not around the eyes, don't look around the eyes, look into my eyes,
you're under.
Look into my eyes, look into my eyes,
the eyes, the eyes, the eyes, not around
the eyes, don't look around the eyes,
look into my eyes, you're under.
Look into my eyes, look into my eyes,
the eyes, the eyes, the eyes, not around
the eyes, don't look around the eyes,
look into my eyes, you're under.
Look into my eyes, look into my eyes,
the eyes, the eyes, the eyes, not
around the eyes, don't look around the
eyes, look into my eyes, you're under.
讨论
textwrap 模块能够以简单直接的方式对文本格式做整理使其适合于打印——尤其是当希望输出结果能很好地显示在终端上时。关于终端的尺寸大小,可以通过 os.get_ terminal_size()来获取。例如:
>>> import os
>>> os.get_terminal_size().columns
80
>>>
fill()方法还有一些额外的选项可以用来控制如何处理制表符、句号等。请参阅 textwrap.TextWrapper 类的文档(http://docs.python.org/3.3/library/ textwrap. html# text w r ap.TextWrapper)以获得进一步的细节。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于