Recipe 1.4. Aligning StringsCredit: Luther Blissett ProblemYou want to align strings: left, right, or center. Solution
That's what the
ljust
,
rjust
, and
center
>>> 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
>>> print 'hej'.center(20, '+') ++++++++hej+++++++++ See AlsoThe Library Reference section on string methods; Java Cookbook recipe 3.5. |
Recipe 1.5. Trimming Space from the Ends of a StringCredit: Luther Blissett Problem
You need to work on a string without regard for any extra leading or trailing spaces a
Solution
That's what the
lstrip
,
rstrip
, and
strip
>>> x = ' hej ' >>> print '', x.lstrip( ), '', x.rstrip( ), '', x.strip( ), '' hej hej hej Discussion
Just as you may need to add space to either end of a string to align that string left, right, or center in a field of fixed width (as covered previously in Recipe 1.4), so may you need to remove all whitespace (blanks, tabs, newlines, etc.) from either or both ends. Because this need is frequent, Python string objects supply this functionality through three of their many methods. Optionally, you may call each of these methods with an argument, a string
>>> x = 'xyxxyy hejyx yyx'
>>> print ''+x.strip('xy')+''
hejyx
Note that in these cases the leading and trailing spaces have been left in the resulting string, as have the ' yx ' that are followed by spaces: only all the occurrences of 'x' and ' y' at either end of the string have been removed from the resulting string. See AlsoThe Library Reference section on string methods; Recipe 1.4; Java Cookbook recipe 3.12. |
Recipe 1.6. Combining StringsCredit: Luther Blissett ProblemYou have several small strings that you need to combine into one larger string. Solution
To join a sequence of small strings into one large string, use the string operator
join
. Say that
pieces
is a list whose items are strings, and you want one big string with all the items
largeString = ''.join(pieces)
To put together pieces stored in a few
largeString = '%s%s something %s yet more' % (small1, small2, small3) Discussion
In Python, the
+
operator
largeString = small1 + small2 + ' something ' + small3 + ' yet more' And similarly, when you have a sequence of small strings named pieces , it seems quite natural to code something like:
largeString = ''
for piece in pieces:
largeString += piece
Or, equivalently, but more fancifully and compactly: import operator largeString = reduce(operator.add, pieces, '')
However, it's very important to realize that none of these seemingly obvious solution is goodthe approaches shown in the "Solution" are
vastly
In Python, string objects are immutable. Therefore, any operation on a string, including string concatenation, produces a new string object, rather than modifying an existing one. Concatenating N strings thus involves building and then immediately throwing away each of N -1 intermediate results. Performance is therefore vastly better for operations that build no intermediate results, but rather produce the desired end result at once.
Python's string-formatting operator
%
is one such operation, particularly suitable when you have a few pieces (e.g., each bound to a different variable) that you want to put together, perhaps with some constant text in addition. Performance is not a major issue for this specific kind of task. However, the
%
operator also has other potential advantages, when compared to an expression that uses multiple + operations on strings. % is more readable, once you get used to it. Also, you don't have to call
str
on pieces that aren't already strings (e.g.,
When you have many small string pieces in a sequence, performance can become a truly important issue. The time needed to execute a loop using
+
or
+=
(or a fancier but equivalent approach using the built-in function
reduce
) grows with the square of the number of
When the pieces are not all available at the same time, but rather come in sequentially from input or computation, use a list as an intermediate data structure to hold the pieces (to add items at the end of a list, you can call the
append
or
extend
Python 2.4 makes a heroic attempt to ameliorate the issue, reducing a little the performance penalty due to such erroneous use of
+=
. While '
'.join
is still way faster and in all ways preferable, at least some newbie or careless programmer gets to waste somewhat fewer machine cycles. Similarly, psyco (a
See AlsoThe Library Reference and Python in a Nutshell sections on string methods, string-formatting operations, and the operator module. |