Python 字符串追加

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