问题
将一些长字符串,以指定的列宽将它们重新格式化。
解决方案
使用 textwrap
模块的 fill
或 wrap
函数
import 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(textwrap.fill(s,width = 60))
如果直接输出的话,可读性会比较差
我们可以使用 fill
函数来将这个长字符串自动切分为若干短字符串,只需要指定 width
即可;
也可以使用 wrap
函数,但是效果是一样的,只不过 wrap
函数返回的是一个列表而不是字符串
我们也可以指定其他一些参数比如 initial_indent
来设置段落的缩进.
总结
如果希望能匹配终端的大小的话,我们可以使用 os.get_terminal_size()
来得到终端的宽度,然后传给 width
textwrap.fill(s, width=os.get_terminal_size().columns)
此外,当我们需要格式化的次数很多时,更高效的方法是先创建一个 TextWrapper
对象,设置好 width
、 initial_indent
等等参数,然后再调用 fill
或者 wrap
方法
wrap = textwrap.TextWrapper(width=60, initial_indent=' '
print(wrap.fill(s))
Look into my eyes, look into my eyes, the eyes, th
eyes, the eyes, not around the eyes, don't look around the
eyes, look into my eyes, you're under.