Quickest way to concatenate strings

Frank Millman frank at chagford.com
Fri Oct 12 01:55:58 EDT 2018


Hi all

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

Interestingly, the 'format' function is slower -

    C:\Users\User>python -m timeit -s "x='a'*500; y='b'*500; z='c'*500" 
'{}{}{}'.format(x, y, z)
    500000 loops, best of 5: 559 nsec per loop

I am using Python 3.7.0 on Windows 10.

Frank Millman





More information about the Python-list mailing list