python string, best way to concat

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Aug 28 10:48:48 EDT 2014


On 28/08/2014 13:08, Roy Smith wrote:
> 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.
>

Which reminds me of 
http://code.activestate.com/recipes/577845-format_iter-easy-formatting-of-arbitrary-iterables/

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list