当前位置 : 主页 > 编程语言 > python >

#yyds干货盘点#python文本自动换行与填充

来源:互联网 收集:自由互联 发布时间:2022-06-15
​​textwrap​​​模块提供了一些快捷函数,以及可以完成所有工作的类​​TextWrapper​​​。 如果你只是要对一两个文本字符串进行自动换行或填充,快捷函数应该就够用了;否则的

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

​​textwrap.​​​​wrap​​(text, width=70, *, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')

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

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

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

​​textwrap.​​​​fill​​(text, width=70, *, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')

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

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

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

​​textwrap.​​​​shorten​​(text, width, *, fix_sentence_endings=False, break_long_words=True, break_on_hyphens=True, placeholder=' [...]')

折叠并截短给定的 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()​​​ 函数之前会被折叠,因此改变 ​​tabsize​​​, ​​expand_tabs​​​, ​​drop_whitespace​​​ 和 ​​replace_whitespace​​ 的值将没有任何效果。

上一篇:04_03取余运算符
下一篇:没有了
网友评论