卖萌的弱渣

I am stupid, I am hungry.

Python: Standard Library II

Output Formatting

  • reprlib can provide abbreviated displays of large containers
1
2
3
>>> import reprlib
>>> reprlib.repr(set('supercalifragi'))
"{'a','c','d','e','f','g',...}"
  • pprint offer more sophisticated control over built-in and user-defined objects.
1
2
3
4
5
6
7
8
9
10
>>> 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 can format paragraphs of text to fit a given screen width
1
2
3
4
5
6
7
8
9
10
>>> 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.

Templating

  • string module includes a Template class to allow users customize The format uses placeholder names formed by $ valid Python identifier
1
2
3
4
>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
  • substitute() method raises a KeyError, when a placeholder is not supplied. safe_substitute() will leave placeholder unchanged if data is missing.
1
2
3
4
5
6
7
8
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
....
KeyError: 'owner'

>>> t.safe_substitute(d)
'Return the unladen swallow to $owner'