textwrap 主要用于对文本进行自动换行、填充和缩进等操作。
wrap()
对 text (字符串) 中的单独段落自动换行以使每行长度最多为 width 个字符。 返回由输出行组成的列表,行尾不带换行符。简单理解就是对原 text 进行重新组织,每 width 个字符进行一次分割。
import textwrap
if __name__ == '__main__':
text = """
hello
world!
"""
print(textwrap.wrap(text, 3)) # [' ', 'hel', 'lo', 'wor', 'ld!']
fill()
对 text 中的单独段落自动换行,并返回一个包含被自动换行段落的单独字符串。
import textwrap
if __name__ == '__main__':
text = """
hello
world!
"""
print(textwrap.fill(text, 3))
#
# hel
# lo
# wor
# ld!
shorten()
折叠并截短给定的 text 以符合给定的 width。将 text 缩短到指定的 width 长度内。如果缩短后的长度还是超过 width 的话,会用表示省略的占位符替换。
import textwrap
if __name__ == '__main__':
text = """
hello
world!
"""
print(textwrap.shorten(text, 11)) # hello [...]
dedent()
移除相同缩进。
import textwrap
if __name__ == '__main__':
text = """
hello
world!
"""
print(textwrap.dedent(text))
#
# hello
# world!
indent()
添加缩进。
import textwrap
if __name__ == '__main__':
text = """
hello
world!
"""
print(textwrap.indent(text, "+"))
#
# + hello
# + world!
对象重用
wrap(), fill() 和 shorten() 的作用方式为创建一个新的 TextWrapper 实例并在其上调用单个方法。每个调用的对象不会重用,使用效率上不高。
import textwrap
if __name__ == '__main__':
text = """
hello
world!
nice
to
meet
you
"""
wrapper = textwrap.TextWrapper(initial_indent="* ", width=7, break_long_words=False, max_lines=3, subsequent_indent="--")
print(wrapper.fill(text))
# * hello
# --world!
# --[...]