Most Efficient Method to Concatenate Strings in Python

后端 未结 3 1084
孤城傲影
孤城傲影 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:27

    For exactly two strings a and b, just use a + b. The alternatives are for joining more than 2 strings, avoiding the temporary str object created by each use of +, as well as the quadratic behavior due to repeatedly copying the contents of earlier operations in the next result.

    (There's also f'{a}{b}', but it's syntactically heavier and no faster than a + b.)

提交回复
热议问题