您好,欢迎访问一九零五行业门户网

如何将多个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 + operatorexample 的中文翻译为:示例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 stringss = t.timer(stmt='amit' + 'jacob' + 'tim' +'tom' + 'mark')# displaying the execution timeprint(execution time = ,s.timeit())
输出execution time = 0.009820308012422174
使用join连接字符串example 的中文翻译为:示例让我们使用.join()方法进行连接。timeit()函数用于测量给定代码的执行时间。
import timeit as t# concatenating 5 stringss = t.timer(stmt=''.join(['amit' + 'jacob' + 'tim' +'tom' + 'mark']))# displaying the execution timeprint(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 timemystr =''a='gjhbxjshbxlasijxkashxvxkahsgxvashxvasxhbasxjhbsxjsabxkjasjbxajshxbsajhxbsajxhbasjxhbsaxjash'l=[]# using the + operatort=time()for i in range(1000): mystr = mystr+a+repr(i)print(time()-t)
输出0.0022547245025634766
concatenate many strings using the joinexample 的中文翻译为:示例我们现在将使用join来连接许多字符串,并检查执行时间。当我们有许多字符串时,连接是更好和更快的选项−
from time import timemystr =''a='gjhbxjshbxlasijxkashxvxkahsgxvashxvasxhbasxjhbsxjsabxkjasjbxajshxbsajhxbsajxhbasjxhbsaxjash'l=[]# using the + operatort=time()for i in range(1000): l.append(a + repr(i))z = ''.join(l)print(time()-t)
输出0.000995635986328125
如上所示,当有许多字符串时,使用join()方法更高效。它执行时间更短。
以上就是如何将多个python字符串高效地连接在一起?的详细内容。
其它类似信息

推荐信息