python string, best way to concat
Roy Smith
roy at panix.com
Thu Aug 28 08:08:22 EDT 2014
In article <63bdccb4-9e34-4e40-b07d-14342e21815f at googlegroups.com>,
peter <peter.mosley at talk21.com> wrote:
> I used to struggle with the concept of ''.join(('hello ','world')) - it
> seemed so convoluted compared with the intuitive 'hello '+'world', and I
> could never remember the syntax. Also, for the strings I was generally using
> the performance penalty was infinitesimal, so I was just adding complexity
> for the sake of the abstract concept of a more 'pythonic' style.
>
> Obviously this isn't going to change, but for concatenating short strings a
> and b is there any practical reason to avoid a+b?
For places where performance doesn't matter, string addition is just
fine. The computer works for you. If you're working for the computer,
you're doing something wrong.
That being said, join is typically used where you have a variable number
of strings in some iterable (e.g. a list of strings). For exactly two
strings, I would have probably written this as:
'%s %s' % (string1, string2)
and if I really wanted to use the join syntax, I would have moved the
delimiter (in this case, a space), into the first string:
' '.join([string1, string2])
Be aware of the various ways, then pick the one that works for you.
More information about the Python-list
mailing list