问题
我们有一些很长很长的字符串,我们希望能够将其重新格式化,按照用户制定的列数来显示。
解决方案
推荐使用 textwrap
模块,下述案例中使用 textwrap.fill(text, width)
函数,其中的两个参数 text
为长文本内容,width
为每一行的长度。
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."
import textwrap
print(textwrap.fill(s, 70))
print("-" * 20)
print(textwrap.fill(s, 40))
结果为:
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.
对于需要在第二行开始前加入空格的,可增加参数 subsequent_indent
print(textwrap.fill(s, 70))
print("*"*20, "添加参数后", "*"*20)
print(textwrap.fill(s, 70, 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.
讨论
textwrap
模块能够以简单直接的方式对文本格式做整理使其适合与设备大小展示内容。结合到实际应用中,其可以通过 os.get_terminal_size()
来获取终端的大小
import os
size = os.get_terminal_size().columns
关于 textwrap.fill()
的更多用法,请参阅 textwrap.TextWrapper
类文档获取更多技术细节。