Combining and Concatenating Strings
Problem
You want to combine many small strings together into a larger string.
Solution
If the strings you wish to combine are found in a sequence or iterable,
the fastest way to combine them is to use the join() method. For example:
>>>parts=['Is','Chicago','Not','Chicago?']>>>' '.join(parts)'Is Chicago Not Chicago?'>>>','.join(parts)'Is,Chicago,Not,Chicago?'>>>''.join(parts)'IsChicagoNotChicago?'>>>
At first glance, this syntax might look really odd, but the join()
operation is specified as a method on strings. This is partly
because the objects you want to join could come from any number of
different data sequences (e.g., lists, tuples, dicts, files, sets, or
generators), and it would be redundant to have join() implemented as
a method on all of those objects separately. So you just specify
the separator string that you want and use the join() method on it
to glue text fragments together.
If you’re only combining a few strings, using + usually works well enough:
>>>a='Is Chicago'>>>b='Not Chicago?'>>>a+' '+b'Is Chicago Not Chicago?'>>>
The + operator also works fine as a substitute for more complicated
string formatting operations. For example:
>>>('{}{}'.format(a,b))Is Chicago Not Chicago?>>>(a+' '+b)Is Chicago ...
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