Thursday, June 3, 2021

Output formatting in Python

Output Formatting
----------------- 

 

`reprlib` 

The reprlib module provides a version of repr() customized for abbreviated 

displays of large or deeply nested containers: 

>>> import reprlib 

>>> reprlib.repr(set('supercalifragilisticexpialidocious')) 

"{'a', 'c', 'd', 'e', 'f', 'g', ...}" 

`pprint` 

A module that handles long strings pretty well. 

>>> 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 be used to print long paragraphs. 

>>> 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` 

Can be used to access culture specific data formats. 

>>> 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' 

No comments:

Post a Comment