【python 内置模块】textwrap

2024-01-20 00:00:00

目录:

textwrap 模块处理文本格式化, 提供了自动换行、填充、缩进调整等一系列功能, 适用于需要控制文本输出宽度和美观排版的场景。

wrap(text, width)

wrap(text, width=70, …), 将文本 text 按最大宽度 width 自动换行, 返回一个由各行字符串组成的列表, 行尾不包含换行符。

import textwrap

sample_text = "The textwrap module can be used to format text for output in situations where pretty-printing is desired."

# 使用 wrap() 返回列表
wrapped_list = textwrap.wrap(sample_text, width=40)
for line in wrapped_list:
    print(f"  '{line}'")

# 输出:
#  'The textwrap module can be used to'
#  'format text for output in situations'
#  'where pretty-printing is desired.'

fill(text, width)

fill(text, width=70, …), 直接返回一个包含自动换行后段落的单一字符串, 各行之间以换行符连接。

wrap() 返回一个列表,fill() 相当于 ‘\n’.join(wrap())。

import textwrap

sample_text = "The textwrap module can be used to format text for output in situations where pretty-printing is desired."

# 使用 fill() 返回字符串
filled_text = textwrap.fill(sample_text, width=40)
print(filled_text)

# 输出:
# The textwrap module can be used to
# format text for output in situations
# where pretty-printing is desired.

dedent(text)

移除多行字符串中每行共同的前缀空白字符 (空格或制表符)。在处理源代码中缩进的三重引号字符串时特别有用, 可以保持代码美观的同时获得无缩进的文本内容。

如下示例: 使用 dedent() 后每行共同的 4 个空格前缀被移除, 但第二行额外的 4 个空格保留。

import textwrap

# 源代码中缩进的多行字符串
indented_text = """
    This is the first line.
        This line is indented more.
    Back to the first level.
"""
print(indented_text)
#    This is the first line.
#        This line is indented more.
#    Back to the first level.

dedented_text = textwrap.dedent(indented_text)
print(dedented_text)
# This is the first line.
#     This line is indented more.
# Back to the first level.

indent(text, prefix, predicate)

indent(text, prefix) 为文本 text 的每一行 (默认排除纯空白行) 开头添加指定的前缀字符串 prefix。

import textwrap

text = "Hello\n\nWorld\n"
print(text)
# Hello
# 
# World


# 默认情况下,不为空行添加前缀
indented_default = textwrap.indent(text, '> ')
print(indented_default)
# > Hello
# 
# > World


# 使用 predicate 为所有行 (包括空行) 添加前缀
indented_all = textwrap.indent(text, '+ ', lambda line: True)
print(indented_all)
# + Hello
# + 
# + World

shorten(text, width, placeholder)

首先将文本中所有连续的空白字符折叠为单个空格,然后检查长度是否满足给定 width。如果满足,则返回折叠后的文本; 否则, 它会从末尾丢弃足够的单词, 使得剩余文本加上占位符 (默认 ‘ […]’, 可以使用 placeholder 参数自定义占位符) 的长度不超过 width。

适用于生成摘要或预览文本。

import textwrap

text = "Hello   world! How are you doing today?"
print(textwrap.shorten(text, width=20))  # 输出: 'Hello world! [...]'
print(textwrap.shorten(text, width=30, placeholder="..."))  # 输出: 'Hello world! How are you...'
print(textwrap.shorten(text, width=60, placeholder="..."))  # 输出: 'Hello world! How are you doing today?'

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: