3.4 Aligning Strings
Credit: Luther Blissett
3.4.1 Problem
You
want to align strings left, right, or center.
3.4.2 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 the starting string with spaces on either or both
sides:
>>> print '|', 'hej'.ljust(20), '|', 'hej'.rjust(20), '|', 'hej'.center(20), '|'
| hej | hej | hej |'.
3.4.3 Discussion
Centering, left-justifying, or right-justifying text comes up
surprisingly often�for example, when you want to print a simple
report with centered page numbers. Because of this, Python string
objects supply this functionality through their methods.
3.4.4 See Also
The Library Reference section on string methods;
Java Cookbook Recipe 3.5.
|