Python 字串物件是不可變的。因此,每次使用 + 運算子連接兩個字串時,都會創建一個新的字串。如果我們必須附加許多字串,使用 + 運算子將在我們獲得最終結果之前不必要地創建許多臨時字串。
Python 字串附加
讓我們看一下一個將字串 ‘n’ 次連接的函數。
def str_append(s, n):
output = ''
i = 0
while i < n:
output += s
i = i + 1
return output
請注意,我定義此函數是為了展示 + 運算子的用法。稍後我將使用 timeit 模組 測試性能。如果您只想要連接一個字串 ‘n’ 次,可以輕鬆使用 s = 'Hi' * 10
。
執行字串附加操作的另一種方法是創建一個 列表,將字串附加到列表中。然後使用 字符串 join() 函數 將它們合併在一起以獲得結果字串。
def str_append_list_join(s, n):
l1 = []
i = 0
while i < n:
l1.append(s)
i += 1
return ''.join(l1)
讓我們測試這些方法,確保它們按預期工作。
if __name__ == "__main__":
print('Append using + operator:', str_append('Hi', 10))
print('Append using list and join():', str_append_list_join('Hi', 10))
# 使用以下內容進行此案例,上述方法是為了
# 使用 timeit 模組檢查性能而創建的
print('Append using * operator:', 'Hi' * 10)
輸出:
Append using + operator: HiHiHiHiHiHiHiHiHiHi
Append using list and join(): HiHiHiHiHiHiHiHiHiHi
Append using * operator: HiHiHiHiHiHiHiHiHiHi
在Python中附加字符串的最佳方法
I have both the methods defined in string_append.py
file. Let’s use timeit module to check their performance.
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hello", 1000)'
1000 loops, best of 5: 174 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hello", 1000)'
1000 loops, best of 5: 140 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hi", 1000)'
1000 loops, best of 5: 165 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hi", 1000)'
1000 loops, best of 5: 139 usec per loop
摘要
如果字符串较少,您可以使用任何方法来附加它们。从可读性的角度来看,对于少量字符串,使用+运算符似乎更好。但是,如果您必须附加大量字符串,则应使用列表和join()函数。
您可以从我们的GitHub存储库中查看完整的Python脚本和更多Python示例。
Source:
https://www.digitalocean.com/community/tutorials/python-string-append