python字符串追加字符
Python string object is immutable. So every time we use + operator to concatenate two strings, a new string is created.
Python字符串对象是不可变的。 因此,每次我们使用+运算符连接两个字符串时,都会创建一个新字符串。
If we have to append many strings, using + operator will unnecessarily create many temporary strings before we have the final result.
如果我们必须追加许多字符串,则使用+运算符将不必要地创建许多临时字符串,直到获得最终结果。
Python字符串追加 (Python String Append)
Let’s look at a function to concatenate a string ‘n’ times.
让我们看一下一个将字符串连接n次的函数。
def str_append(s, n):
output = ''
i = 0
while i < n:
output += s
i = i + 1
return output
s = 'Hi' * 10
.
s = 'Hi' * 10
轻松实现。
Another way to perform string append operation is by creating a list and appending strings to the list. Then use string join() function to merge them together to get the result string.
执行字符串追加操作的另一种方法是通过创建列表并将字符串追加到列表中。 然后使用字符串join()函数将它们合并在一起以获得结果字符串。
def str_append_list_join(s, n):
l1 = []
i = 0
while i < n:
l1.append(s)
i += 1
return ''.join(l1)
Let's test these methods to make sure they are working as expected.
让我们测试这些方法,以确保它们按预期工作。
if __name__ == "__main__":
print('Append using + operator:', str_append('Hi', 10))
print('Append using list and join():', str_append_list_join('Hi', 10))
# use below for this case, above methods are created so that we can
# check performance using timeit module
print('Append using * operator:', 'Hi' * 10)
Output:
输出:
Append using + operator: HiHiHiHiHiHiHiHiHiHi
Append using list and join(): HiHiHiHiHiHiHiHiHiHi
Append using * operator: HiHiHiHiHiHiHiHiHiHi
在Python中附加字符串的最佳方法 (Best way to append strings in Python)
I have both the methods defined in string_append.py
file. Let's use timeit module to check their performance.
我在string_append.py
文件中定义了两种方法。 让我们使用timeit模块检查其性能。
$ 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
摘要 (Summary)
If there are few strings, then you can use any method to append them. From a readability perspective, using + operator seems better for few strings. However, if you have to append a lot of string, then you should use the list and join() function.
如果字符串很少,则可以使用任何方法附加它们。 从可读性的角度来看,对于少数几个字符串,使用+运算符似乎更好。 但是,如果必须附加很多字符串,则应使用list和join()函数。
python字符串追加字符