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中文網其他相關文章!