11.1. 格式化输出

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

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

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

  1. >>> import pprint
  2. >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
  3. ... 'yellow'], 'blue']]]
  4. ...
  5. >>> pprint.pprint(t, width=30)
  6. [[[['black', 'cyan'],
  7. 'white',
  8. ['green', 'red']],
  9. [['magenta', 'yellow'],
  10. 'blue']]]

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

  1. >>> import textwrap
  2. >>> doc = """The wrap() method is just like fill() except that it returns
  3. ... a list of strings instead of one big string with newlines to separate
  4. ... the wrapped lines."""
  5. ...
  6. >>> print(textwrap.fill(doc, width=40))
  7. The wrap() method is just like fill()
  8. except that it returns a list of strings
  9. instead of one big string with newlines
  10. to separate the wrapped lines.

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

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