FreezeJ' Blog

python textwrap模块

2020-11-03

textwrap — 文本自动换行与填充
官方文档:https://docs.python.org/zh-cn/3/library/textwrap.html

文本裁切

wrap 根据限定长度(width)裁切空字符,返回一个列表
fill 根据限定长度(width)裁切空字符,返回一个完整字符串
shorten 根据限定长度(width)裁切空字符,去掉多出长度的部分

示例代码

import textwrap
txt = 'This above all: to thine own self be true, and it must follow, as the night the day, thou canst not then be false to any man.'
print(textwrap.wrap(txt, width=30))
print(textwrap.fill(txt, width=30))
print(textwrap.shorten(txt, width=30, placeholder="..."))

输出结果

# wrap
['This above all: to thine own', 'self be true, and it must', 'follow, as the night the day,', 'thou canst not then be false', 'to any man.']

# fill
This above all: to thine own
self be true, and it must
follow, as the night the day,
thou canst not then be false
to any man.

# shorten
This above all: to thine ...

前缀处理

dedent移除text中每一行的任何相同前缀空白符,对于嵌套在代码里面的三引号的文本非常友好,不需要顶格显示
indentprefix添加到 text 中选定行的开头

示例代码

import textwrap
txt = '''
         This above all: to thine own
         self be true, and it must
         follow, as the night the day,
         thou canst not then be false
         to any man.'''
print(txt)
dedent_txt = textwrap.dedent(txt)
print(dedent_txt)
indent_txt = textwrap.indent(dedent_txt, prefix='> ', predicate=lambda line: line != '\n')
print(indent_txt)

输出结果

# txt
         This above all: to thine own
         self be true, and it must
         follow, as the night the day,
         thou canst not then be false
         to any man.

# dedent_txt
This above all: to thine own
self be true, and it must
follow, as the night the day,
thou canst not then be false
to any man.

# indent_txt
> This above all: to thine own
> self be true, and it must
> follow, as the night the day,
> thou canst not then be false
> to any man.
Tags: Python