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 −
让我们开始示例
Let us concatenate using the + operator. The timeit() is used to measure the execution time taken by the given code −
import timeit as t # Concatenating 5 strings s = t.Timer(stmt="'Amit' + 'Jacob' + 'Tim' +'Tom' + 'Mark'") # Displaying the execution time print("Execution Time = ",s.timeit())
Execution Time = 0.009820308012422174
让我们使用.join()方法进行连接。timeit()函数用于测量给定代码的执行时间。
import timeit as t # Concatenating 5 strings s = t.Timer(stmt="''.join(['Amit' + 'Jacob' + 'Tim' +'Tom' + 'Mark'])") # Displaying the execution time print("Execution Time = ",s.timeit())
Execution Time = 0.0876248900021892
As shown above, using the + operator is more efficient. It takes less time for execution.
我们将现在连接许多字符串并使用时间模块检查执行时间−
from time import time myStr ='' a='gjhbxjshbxlasijxkashxvxkahsgxvashxvasxhbasxjhbsxjsabxkjasjbxajshxbsajhxbsajxhbasjxhbsaxjash' l=[] # Using the + operator t=time() for i in range(1000): myStr = myStr+a+repr(i) print(time()-t)
0.0022547245025634766
我们现在将使用Join来连接许多字符串,并检查执行时间。当我们有许多字符串时,连接是更好和更快的选项−
from time import time myStr ='' a='gjhbxjshbxlasijxkashxvxkahsgxvashxvasxhbasxjhbsxjsabxkjasjbxajshxbsajhxbsajxhbasjxhbsaxjash' l=[] # Using the + operator t=time() for i in range(1000): l.append(a + repr(i)) z = ''.join(l) print(time()-t)
0.000995635986328125
如上所示,当有许多字符串时,使用join()方法更高效。它执行时间更短。
以上是如何将多个Python字符串高效地连接在一起?的详细内容。更多信息请关注PHP中文网其他相关文章!