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

WBOY
发布: 2023-08-25 17:37:06
转载
731人浏览过

如何将多个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()函数用于测量给定代码的执行时间。

立即学习Python免费学习笔记(深入)”;

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字符串高效地连接在一起?的详细内容,更多请关注php中文网其它相关文章!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号