Python Tutorial (2.7.1) by Python Software Foundation

Python Tutorial (2.7.1) by Python Software Foundation

Author:Python Software Foundation
Language: eng
Format: mobi
Tags: CS, Programming, IT
Publisher: Python Software Foundation
Published: 2011-01-18T23:00:00+00:00


Here are two ways to write a table of squares and cubes:

>>> for x in range(1, 11):

... print repr(x).rjust(2), repr(x*x).rjust(3),

... # Note trailing comma on previous line

... print repr(x*x*x).rjust(4)

...

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

>>> for x in range(1,11):

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

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

(Note that in the first example, one space between each column was added by the way print works: it always adds spaces between its arguments.)

This example demonstrates the rjust() method of string objects, which right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods ljust() and center(). These methods do not write anything, they just return a new string. If the input string is too long, they don't truncate it, but return it unchanged; this will mess up your column lay-out but that's usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in x.ljust(n)[:n].)

There is another method, zfill(), which pads a numeric string on the left with zeros. It understands about plus and minus signs:

>>> '12'.zfill(5)

'00012'

>>> '-3.14'.zfill(7)

'-003.14'

>>> '3.14159265359'.zfill(5)

'3.14159265359'



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.