11.1. 格式化输出
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 strings
- instead of one big string with newlines
- to 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'