A formatting example using string methods

You can also use string methods to write code that prints a table of powers, similar to the one in the previous section, "Formatting with multiple data items in a tuple." The rjust() method right-justifies the string within an area the size of the number of spaces specified in its argument.

Note that this code has more lines than the code written with the % operator and tuples. If you're concerned about reducing the size of your programs, the % operator might be the way to go.

print x, y.rjust(4), z.rjust(6) print "=" * 14 for n in range(1,6): nn = str(n**2) nnn = str(n**n)

Here's what it prints:

x

x**2

x**x

1

1

1

2

4

4

3

9

27

4

16

256

5

25

3125

Was this article helpful?

0 0

Post a comment