python string, best way to concat

Chris Angelico rosuav at gmail.com
Thu Aug 28 04:58:15 EDT 2014


On Thu, Aug 28, 2014 at 6:43 PM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
> On 28/08/2014 09:30, peter 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?
>>
>> Peter
>>
>
> Please quote context, there's some smart people on this list but none of
> them are mind readers :)

Speak for yourself! I play a mind reader on Threshold RPG (in fact,
one of the highest level psions on the game), and several of my
brothers tell me I can pull the same tricks in real life. Or maybe I'm
just really good at knowing what problems they're having, even before
they recognize the problems themselves...

But Peter, no - no reason to avoid it for concatenating two strings.
The advantages of join() are visible when you have huge numbers of
strings; plus it's more readable than repeating a separator lots of
times, especially if you're working with variable numbers of list
elements:

https://github.com/Rosuav/runningtime/blob/master/runningtime.py#L211

The debug info is collected in a list (appending each item, and quite
a few of them are elided if they're some kind of default), and then
they're joined with ', ' as the separator. I could use string
appending for that, but there's no point; it's more readable this way.
Performance doesn't matter at all here, just readability.

ChrisA



More information about the Python-list mailing list