python textwrap文本包装和填充的简单示例
感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编来看看吧。 对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编两巴掌来看看吧! 代码实例:
段落填充:
执行结果: # pythontextwrap_fill.py No dedent: The textwrap module can be used to format text for outputin situations where pretty- printing is desired. It offers programmatic functionalitysimilar to the paragraph wrapping or fillingfeatures found in many text editors. 结果为左对齐,第一行有缩进。行中的空格继续保留。 移除缩进:
执行结果: # pythontextwrap_dedent.py Dedented:
The textwrapmodule can be used to format text for output in situations wherepretty-printing is desired. It offers programmaticfunctionality similar to the paragraph wrapping or fillingfeatures found in many text editors. 这样第一行就不会缩进。 结合移除缩进和填充:
执行结果: # pythontextwrap_fill_width.py 45 Columns:
The textwrapmodule can be used to format text for output insituations where pretty- printing isdesired. It offers programmatic functionalitysimilar to the paragraph wrapping orfilling features found in many text editors.
70 Columns:
The textwrapmodule can be used to format text for output in situations wherepretty-printing is desired. It offersprogrammatic functionality similarto the paragraph wrapping or filling features found in many texteditors. 悬挂缩进:悬挂缩进第一行的缩进小于其他行的缩进。
其中的’’*4还可以使用其他字符代替。 TextWrap提供函数wrap()和fill(),以及TextWrapper类,工具函数dedent(). 通常包装或者填充一两个字符串使用wrap()和fill()。其他情况使用TextWrapper更高效。 textwrap.wrap(text[,width[,...]]) 包装单个段落(text为输入,系字符串),每行最长宽度width。返回输出行的列表,最后行无换行符。Width默认70。 textwrap.fill(text[,...]]) 包装单段文字,并返回包含包裹段落的字符串。实际上是"n".join(wrap(text,...))的缩写。wrap() and fill()创建TextWrapper实例,并调用一个方法。这些实例不被重用,所以包装/填充很多文本字符串要构造自己的TextWrapper对象更有效。TextWrapper.break_long_words设置是否拆长单词。 textwrap.dedent(text) 反缩进去除每行行首的空白。这方便显示三引号中的内容而不修改其源代码中的缩进。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |