Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Saturday 22 December 2012

Fancy Formatting using Python

December 22, 2012 Posted by Dinesh 1 comment

Its quite easy in python to pretty print the output...
Here are two ways to write a table of squares and cubes:
for x in range(1, 6):
...     print repr(x).rjust(2), repr(x*x).rjust(3),repr(x*x*x).rjust(4)
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125

>>> for x in range(1,6):
...     print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
_____________________________________________________________________________________________

similar to rjust function, there are ljsut and center, which justifies the string with spaces (if filler is not specified)

>>> print 'PYTHON'.center(15)
     PYTHON  
>>>
>>> print 'PYTHON'.center(15, '*' )
*****PYTHON****
_____________________________________________________________________________________________

We can use the brackets ( {} ) to format the data.
The brackets and characters within them (called format fields) are replaced  with the objects passed
into the str.format() method.
A number in the brackets refers to the position of the object passed into the str.format() method.

>>> print 'The story of {0}, {1}, and {other}' .format('Bill', 'Manfred', other='Georg')
The story of Bill, Manfred, and Georg
_____________________________________________________________________________________________

An optional ':' and format specifier can follow the field name. This allows greater control over how the value is formatted. The following example rounds Pi to three places after the decimal.

>>> import math
>>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
The value of PI is approximately 3.142.


Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making tables pretty.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...             print '{0:10} ==> {1:10d}'.format(name, phone)
...
Jack        ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127

___________________________________________________________________________

The % operator can also be used for string formatting in place of str.format() . but it is old fashion. this old style of formatting will eventually be removed from the language. 

>>> import math
>>> print 'The value of PI is approximately %.3f' % math.pi
The value of PI is approximately 3.142



Ref: Python v2.7 Documentation

1 comment:

  1. Thank you. I'll surely update the blog as and when I get time.

    ReplyDelete