如何将多个Python字符串高效地连接在一起?

2023年 8月 27日 19.8k 0

如何将多个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 + Operator

Example

的中文翻译为:

示例

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 strings
s = t.Timer(stmt="'Amit' + 'Jacob' + 'Tim' +'Tom' + 'Mark'")

# Displaying the execution time
print("Execution Time = ",s.timeit())

登录后复制

输出

Execution Time = 0.009820308012422174

登录后复制

使用Join连接字符串

Example

的中文翻译为:

示例

让我们使用.join()方法进行连接。timeit()函数用于测量给定代码的执行时间。

import timeit as t

# Concatenating 5 strings
s = t.Timer(stmt="''.join(['Amit' + 'Jacob' + 'Tim' +'Tom' + 'Mark'])")

# Displaying the execution time
print("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 time

myStr =''
a='gjhbxjshbxlasijxkashxvxkahsgxvashxvasxhbasxjhbsxjsabxkjasjbxajshxbsajhxbsajxhbasjxhbsaxjash'
l=[]

# Using the + operator
t=time()
for i in range(1000):
myStr = myStr+a+repr(i)
print(time()-t)

登录后复制

输出

0.0022547245025634766

登录后复制

Concatenate Many Strings using the Join

Example

的中文翻译为:

示例

我们现在将使用Join来连接许多字符串,并检查执行时间。当我们有许多字符串时,连接是更好和更快的选项−

from time import time

myStr =''
a='gjhbxjshbxlasijxkashxvxkahsgxvashxvasxhbasxjhbsxjsabxkjasjbxajshxbsajhxbsajxhbasjxhbsaxjash'
l=[]

# Using the + operator
t=time()
for i in range(1000):
l.append(a + repr(i))
z = ''.join(l)
print(time()-t)

登录后复制

输出

0.000995635986328125

登录后复制

如上所示,当有许多字符串时,使用join()方法更高效。它执行时间更短。

以上就是如何将多个Python字符串高效地连接在一起?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论