如何将多个Python字符串高效地连接在一起?

如何将多个Python字符串高效地连接在一起?

The most efficient way to concatenate many Python Strings together depends on what task you want to fulfil. We will see two ways with four examples and compare the execution time −

  • 当字符串较少时,使用 + 运算符进行连接
  • Concatenate using the Joins when the strings are less
  • 当字符串较多时,使用 + 运算符进行连接
  • 当字符串很多时,使用连接操作符进行连接

让我们开始示例

Concatenate Strings using the + Operator

Example

Let us concatenate using the + operator. The timeit() is used to measure the execution time taken by the given code −

import timeit as t 1. Concatenating 5 strings s = t.Timer(stmt="'Amit' + 'Jacob' + 'Tim' +'Tom' + 'Mark'") 1. Displaying the execution time print("Execution Time = ",s.timeit()) 登录后复制