卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

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

如何将多个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()方法更高效。它执行时间更短。

卓越飞翔博客
上一篇: PHP连接百度文心一言API获取特定类型句子的实现方式
下一篇: Python与百度AI接口对接的深入指南分享与技巧总结
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏