osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Quickest way to concatenate strings


"Dennis Lee Bieber"  wrote in message 
news:cnk0sdl5a7p17framc5er811p1230mpmrk at 4ax.com...

> On Fri, 12 Oct 2018 07:55:58 +0200, "Frank Millman" <frank at chagford.com>
> declaimed the following:
>
> >I have often read that the quickest way to concatenate a number of 
> >strings
> >is to place them in a list and 'join' them -
> >
> >    C:\Users\User>python -m timeit -s "x='a'*500; y='b'*500; z='c'*500"
> >''.join([x, y, z])
> >    500000 loops, best of 5: 307 nsec per loop
> >
> >I seem to have found a quicker method, using the new 'f' format 
> >operator -
> >
> >    C:\Users\User>python -m timeit -s "x='a'*500; y='b'*500; z='c'*500"
> >f'{x}{y}{z}'
> >    1000000 loops, best of 5: 226 nsec per loop
>
> But your format operator is tied to just a specific number of
> substrings.
>
> The list/join algorithm works when the substrings are gathered on an
> ad-hoc basis, and the total number of items is unknown.
>
> collect = []
> while True:
> ln = raw_input("enter a string (empty line to exit)> ").strip()
> #yes, Python 2.x
> if not ln: break
> collect.append(ln)
>
> result = "".join(collect)

That makes sense, thanks.

My use case is that I am building a string from a number of building 
blocks - some of them literal strings, some of them string objects.

As Thomas says, I could have just used the '+' operator. In practice I was 
building a list and then joining it. It turns out that the 'f' operator is 
faster than both of these methods in my particular case.

Frank