Combining Strings
Credit: Luther Blissett
Problem
You have several small strings that you need to combine into one larger string.
Solution
The + operator
concatenates strings and therefore offers seemingly obvious solutions
for putting small strings together into a larger one. For example,
when you have all the pieces at once, in a few variables:
largeString = small1 + small2 + ' something ' + small3 + ' yet more'
Or when you have a sequence of small string pieces:
largeString = ''
for piece in pieces:
largeString += pieceOr, equivalently, but a bit more compactly:
import operator largeString = reduce(operator.add, pieces, '')
However, none of these solutions is generally optimal. To put
together pieces stored in a few variables, the string-formatting
operator % is often best:
largeString = '%s%s something %s yet more' % (small1, small2, small3)
To join a sequence of small strings into one large string, the string
operator join is invariably best:
largeString = ''.join(pieces)
Discussion
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 quite a bit better for
operations that build no intermediate results, but rather produce the
desired end result at once. The string-formatting operator
% is one such operation, particularly ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access