Most Efficient Method to Concatenate Strings in Python

后端 未结 3 1092
孤城傲影
孤城傲影 2021-01-20 23:50

At the time of asking this question, I\'m using Python 3.8

When I say efficient, I\'m only referring to the speed at which the strings are concatenated,

3条回答
  •  攒了一身酷
    2021-01-21 00:40

    from datetime import datetime
    a = "start"
    b = " end"
    
    start = datetime.now()
    print(a+b)
    print(datetime.now() - start)
    
    start = datetime.now()
    print("".join((a, b)))
    print(datetime.now() - start)
    
    start = datetime.now()
    print('{0}{1}'.format(a, b))
    print(datetime.now() - start)
    
    # Output
    # start end
    # 0:00:00.000056
    # start end
    # 0:00:00.000014
    # start end
    # 0:00:00.000014
    

    Looks like .join() and .format() are basically the same and 4x faster. An F string, eg:

    print(f'{a} {b}')
    

    is also a very quick and clean method, especially when working with more complex formats.

提交回复
热议问题