Recipe 1.4. Aligning Strings
Credit: Luther Blissett
Problem
You want to align strings: left, right, or center.
Solution
That's
what the ljust, rjust, and
center methods of string objects are for. Each
takes a single argument, the width of the string you want as a
result, and returns a copy of the starting string with spaces added
on either or both sides:
>>> print '|', 'hej'.ljust(20), '|',
'hej'.rjust(20), '|', 'hej'.center(20), '|'
| hej | hej | hej |
Discussion
Centering, left-justifying, or right-justifying text comes up
surprisingly oftenfor example, when you want to print a simple
report with centered page numbers in a monospaced font. Because of
this, Python string objects supply this functionality through three
of their many methods. In Python 2.3, the padding character is always
a space. In Python 2.4, however, while space-padding is still the
default, you may optionally call any of these methods with a second
argument, a single character to be used for the
padding:
>>> print 'hej'.center(20, '+')
++++++++hej+++++++++
See Also
The Library Reference section on string
methods; Java Cookbook recipe 3.5.