首頁  >  文章  >  後端開發  >  如何將多個Python字串高效率地連接在一起?

如何將多個Python字串高效率地連接在一起?

WBOY
WBOY轉載
2023-08-25 17:37:06699瀏覽

如何將多個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

# 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連接字串

Example

的中文翻譯為:

範例

讓我們使用.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.

使用 運算子連接多個字串

Example

的中文翻譯為:

範例

我們將現在連接許多字串並使用時間模組檢查執行時間−

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

Concatenate Many Strings using the Join

Example

的中文翻譯為:

範例

我們現在將使用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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除