[Tutor] need help reading the code
Alan Gauld
alan.gauld at btinternet.com
Tue Jul 8 00:21:40 CEST 2014
On 07/07/14 19:29, keith papa wrote:
# decimal (.) precision of 3 for float '0.333'
>>> print '{0:.3f}'.format(1.0/3)
The best way to see how this works is to try it
with different values:
>>> print('{0:.3f}'.format(1.0/3))
0.333
>>> print('{0:.5f}'.format(1.0/3))
0.33333
>>> print('{0:.1f}'.format(1.0/3))
0.3
>>> print('{0:.5f}'.format(1.0/2))
0.50000
>>>
Look at how many digits appear after the decimal
point in each case.
# fill with underscores (_) with the text centered
# (^) to 11 width '___hello___'
>>> print '{0:_^11}'.format('hello')
Again, try it out with different values.
The tricky thing here is that he is showing 3 different features in one
example.
Try breaking them down into 3 different sets then
building them back up:
set width of field:
>>> print('{:11}'.format('hello'))
hello
>>> print('{:3}'.format('hello'))
hello
>>>
Hmmm, Doesn't seem to do anything...Lets add some justification
>>> print('{:<11}'.format('hello'))
hello
>>> print('{:>11}'.format('hello'))
hello
>>> print('{:^11}'.format('hello'))
hello
Somethings happening, but to really see what it is...
add a padding character so you see the 'spaces;:
>>> print('{:_>11}'.format('hello'))
______hello
>>> print('{:_<11}'.format('hello'))
hello______
>>> print('{:_^11}'.format('hello'))
___hello___
Which is where we came in...
Try different padding characters and change the width values.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list