Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the most efficient way to concatenate strings in Python

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "what is the most efficient way to connect strings in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

An experiment has been done today, and the result may surprise you.

Def join (n):

S = "" .join ((str (I) for i in range (n)

Def format (n):

("{}" * n) .format (* (i for i in range (n)

Def plus (n):

S = ""

For i in range (n):

S + = str (I)

The above three functions represent concatenating strings with "join" and "format" and "+" operations, respectively. From 0 to n, a total of n numbers are concatenated to form a new string, such as 1234567891011. N .

Here is the test script:

Each group took 15 sample data, respectively, using 1, 2, 4, and 8, respectively. 8192 numbers are connected, and the statistics show that when the amount of data is very small, there is almost no difference in efficiency, and when less than 20 strings are concatenated, using "+" is even more efficient, but with the increase in the number of strings, the "join" method works, while using "+" is getting slower and slower. This is basically the same whether it's python2 or python3.

Python2.7.10

Python3.6.0

So the conclusion is: if there are only a few or a dozen concatenated strings, you can connect them through "+". After all, this way is more straightforward, and after more than a certain number, you should use the "join" method. Only when you operate big data, the comparison between the two is obvious.

This is the end of the content of "what is the most efficient way to concatenate strings in Python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report