问题
你有一些长字符串,想以指定的列宽将它们重新格式化。
解决方案
使用textwrap
模块的fill
或wrap
函数
假设有一个很长的字符串
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)
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.
复制代码
我们可以使用fill
函数来将这个长字符串自动切分为若干短字符串,只需要指定width
即可
>>> print(textwrap.fill(s, width=60))
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.
复制代码
也可以使用wrap
函数,但是效果是一样的,只不过wrap
函数返回的是一个列表而不是字符串
我们也可以指定其他一些参数比如initial_indent
来设置段落的缩进,更多参数见讨论部分的链接
>>> print(textwrap.fill(s, width=60, initial_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.
复制代码
讨论
如果希望能匹配终端的大小的话,我们可以使用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, the
eyes, the eyes, not around the eyes, don't look around the
eyes, look into my eyes, you're under.
复制代码
关于TextWrapper
的其他参数见:
https://docs.python.org/3/library/textwrap.html
来源
Python Cookbook
关注
欢迎关注我的微信公众号:python每日一练