Python 字符串追加

Python 字符串对象是不可变的,所以每当我们使用 + 操作员连接两个字符串时,就会创建一个新的字符串。

Python String 附件

让我们来看看一个函数来连接一个字符串n时间。

1def str_append(s, n):
2    output = ''
3    i = 0
4    while i < n:
5        output += s
6        i = i + 1
7    return output

请注意,我正在定义这个函数以展示 + 运算符的使用情况。我以后会使用 timeit 模块来测试性能。

另一种执行 string 附件操作的方法是创建一个 list并将字符串附加到列表中,然后使用 string join() 函数将它们合并到一起以获得结果字符串。

1def str_append_list_join(s, n):
2    l1 = []
3    i = 0
4    while i < n:
5        l1.append(s)
6        i += 1
7    return ''.join(l1)

让我们测试这些方法,以确保它们按预期工作。

1if __name__ == "__main__":
2    print('Append using + operator:', str_append('Hi', 10))
3    print('Append using list and join():', str_append_list_join('Hi', 10))
4    # use below for this case, above methods are created so that we can
5    # check performance using timeit module
6    print('Append using * operator:', 'Hi' * 10)

输出:

1Append using + operator: HiHiHiHiHiHiHiHiHiHi
2Append using list and join(): HiHiHiHiHiHiHiHiHiHi
3Append using * operator: HiHiHiHiHiHiHiHiHiHi

在Python中添加字符串的最佳方法

我在 string_append.py 文件中定义了这两种方法,让我们使用 timeit 模块来检查它们的性能。

1$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hello", 1000)' 
21000 loops, best of 5: 174 usec per loop
3$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hello", 1000)'
41000 loops, best of 5: 140 usec per loop
5
6$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hi", 1000)' 
71000 loops, best of 5: 165 usec per loop
8$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hi", 1000)'
91000 loops, best of 5: 139 usec per loop

python string append, python add to string

摘要

如果有很少的字符串,那么你可以使用任何方法来附加它们。从可读性的角度来看,使用 + 运算器似乎更适合几个字符串,但是,如果你需要附加很多字符串,那么你应该使用列表和 join() 函数。

您可以从我们的 GitHub 存储库中查阅完整的 Python 脚本和更多 Python 示例。

Published At
Categories with 技术
comments powered by Disqus