Quickest way to concatenate strings

Frank Millman frank at chagford.com
Fri Oct 12 06:30:27 EDT 2018


"Dennis Lee Bieber" wrote in message 
news:cnk0sdl5a7p17framc5er811p1230mpmrk at 4ax.com...
> On 2018年10月12日 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


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /