0
点赞
收藏
分享

微信扫一扫

文本自动换行与填充

textwrap 模块提供了一些快捷函数,以及可以完成所有工作的类 TextWrapper。 如果你只是要对一两个文本字符串进行自动换行或填充,快捷函数应该就够用了;否则的话,你应该使用 TextWrapper 的实例来提高效率。

textwrap.wrap(textwidth=70*initial_indent=''subsequent_indent=''expand_tabs=Truereplace_whitespace=Truefix_sentence_endings=Falsebreak_long_words=Truedrop_whitespace=Truebreak_on_hyphens=Truetabsize=8max_lines=Noneplaceholder=' [...]')

对 text (字符串) 中的单独段落自动换行以使每行长度最多为 width 个字符。 返回由输出行组成的列表,行尾不带换行符。

与 TextWrapper 的实例属性对应的可选的关键字参数,具体文档见下。

请参阅 TextWrapper.wrap() 方法了解有关 wrap() 行为的详细信息。

textwrap.fill(textwidth=70*initial_indent=''subsequent_indent=''expand_tabs=Truereplace_whitespace=Truefix_sentence_endings=Falsebreak_long_words=Truedrop_whitespace=Truebreak_on_hyphens=Truetabsize=8max_lines=Noneplaceholder=' [...]')

对 text 中的单独段落自动换行,并返回一个包含被自动换行段落的单独字符串。 fill() 是以下语句的快捷方式

"\n".join(wrap(text, ...))

特别要说明的是,fill() 接受与 wrap() 完全相同的关键字参数。

textwrap.shorten(textwidth*fix_sentence_endings=Falsebreak_long_words=Truebreak_on_hyphens=Trueplaceholder=' [...]')

折叠并截短给定的 text 以符合给定的 width

首先,将折叠 text 中的空格(所有连续空格替换为单个空格)。 如果结果能 width 则将其返回。 否则将丢的以加 placeholder 能 width

>>> textwrap.shorten("Hello  world!", width=12)
'Hello world!'
>>> textwrap.shorten("Hello  world!", width=11)
'Hello [...]'
>>> textwrap.shorten("Hello world", width=10, placeholder="...")
'Hello...'

可选的关键字参数对应于 TextWrapper 的实际属性,具体见下文。 请注意文本在被传入 TextWrapper 的 fill() 函数之前会被折叠,因此改变 tabsizeexpand_tabsdrop_whitespace 和 replace_whitespace 的值将没有任何效果。

举报

相关推荐

0 条评论