#yyds干货盘点#python格式化输出

网友投稿 305 2022-08-23


#yyds干货盘点#python格式化输出

​​reprlib​​​ 模块提供了一个定制化版本的 ​​repr()​​ 函数,用于缩略显示大型或深层嵌套的容器对象:

>>> import reprlib>>> reprlib.repr(set('supercalifragilisticexpialidocious'))"{'a', 'c', 'd', 'e', 'f', 'g', ...}"

​​pprint​​ 模块提供了更加复杂的打印控制,其输出的内置对象和用户自定义对象能够被解释器直接读取。当输出结果过长而需要折行时,“美化输出机制”会添加换行符和缩进,以更清楚地展示数据结构:

>>> import pprint>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',... 'yellow'], 'blue']]]...>>> pprint.pprint(t, width=30)[[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]

​​textwrap​​ 模块能够格式化文本段落,以适应给定的屏幕宽度:

>>> import textwrap>>> doc = """The wrap() method is just like fill() except that it returns... a list of strings instead of one big string with newlines to separate... the wrapped lines."""...>>> print(textwrap.fill(doc, width=40))The wrap() method is just like fill()except that it returns a list of stringsinstead of one big string with newlinesto separate the wrapped lines.

​​locale​​ 模块处理与特定地域文化相关的数据格式。locale 模块的 format 函数包含一个 grouping 属性,可直接将数字格式化为带有组分隔符的样式:

>>> import locale>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')'English_United States.1252'>>> conv = locale.localeconv() # get a mapping of conventions>>> x = 1234567.8>>> locale.format("%d", x, grouping=True)'1,234,567'>>> locale.format_string("%s%.*f", (conv['currency_symbol'],... conv['frac_digits'], x), grouping=True)'$1,234,567.80'


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Pytest学习-python读取ini配置文件(怎么新建pytest的ini文件)
下一篇:python - lambda函数、map函数、filter函数(python怎么读)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~