Pytho​n格式化输出

2023-10-12 27

一、reprlib模块

reprlib模块提供了一个定制化版本的 repr() 函数,提供了定制化版本的 repr() 函数,用于缩略显示大型或深层嵌套的容器对象。使用 reprlib.repr() 函数可以返回一个对象的字符串表示形式,该字符串表示形式可以通过 repr() 函数重新转换回原始对象。

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

二、pprint模块

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模块

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 strings
instead of one big string with newlines
to separate the wrapped lines.

四、locale模块

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_string("%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'
  • 广告合作

  • QQ群号:707632017

温馨提示:
1、本网站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。邮箱:2942802716#qq.com(#改为@)。 2、本站原创内容未经允许不得转裁,转载请注明出处“站长百科”和原文地址。
Pytho​n格式化输出
上一篇: Pytho​n标准库
Pytho​n格式化输出
下一篇: Python模板