a = """对字符串中的单独段落自动换行以使每行长度最多为 width个字符。返回由输出行组成的列表,行尾不带换行符。"""
import textwrap
# 1.wrap
b = textwrap.wrap(a, 10)
print("\n".join(b))
"""
对字符串中的单独段落
自动换行以使每行长度
最多为 width个
字符。返回由输出行组
成的列表,行尾不带换
行符。
"""
# 2.shorten
# 将折叠 text 中的空格(所有连续空格替换为单个空格)。
# 如果结果能适合 width 则将其返回。
# 否则将丢弃足够数量的末尾单词以使得剩余单词加 placeholder 能适合 width
b = textwrap.shorten("abc defg", width=10)
print(b) #abc defg
b = textwrap.shorten("abc defghijk", width=10)
print(b) #abc [...]
b = textwrap.shorten("abc defghijk", width=10, placeholder="..")
print(b) #abc..
# 3.dedent
# 移除 text 中每一行的任何相同前缀空白符。
# 可以用来清除三重引号字符串行左侧空格,而仍然在源码中显示为缩进格式。
s = '''
hello
world
'''
print(repr(s)) #'\n hello\n world\n '
print(repr(textwrap.dedent(s))) #'\nhello\n world\n'
# 4. indent
# 将prefix添加到text中的每一行(不只由空白符组成)
# prefix:要添加的前缀
# predicate 参数可用来控制哪些行要缩进
s = '''
hello
hell
world
'''
print(textwrap.indent(s, prefix="+", predicate=lambda line: len(line.strip())>4))
"""
+ hello
hell
+ world
"""
Python文本自动换行与填充
最新推荐文章于 2024-06-17 09:58:27 发布