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

Why not use + to connect strings in Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "why not use + to connect strings in Python", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "Why not use + to connect strings in Python"!

began

As a beginner, or someone who has just switched from another programming language that uses the "+" concatenation string, it is easy to write code like this:

str1 ="I love" str2 ="Python. " print(str1 + str2)

But over time, you may find that others write like this:

str1 ="I love" str2 ="Python. " print(''.join([str1,str2]))

To be honest, when I first saw the above method, I thought it was neither intuitive nor aesthetically pleasing.

Concatenate multiple strings

The twist occurred shortly after, when I needed to concatenate multiple strings in a list.

strs = ['Life','is','short','I','use','Python']

Initially, I did this:

strs = ['Life', 'is', 'short,','I', 'use', 'Python']def join_strs(strs): result = '' for s in strs: result += ' ' + s return result[1:]join_strs(strs)

I have to write a for loop to concatenate strings one by one. Also, I need to delete the spaces I added at the beginning of the result string, because all strings need to be preceded by spaces, not just the beginning.

Perhaps you have other solutions, such as adding the index to the for loop so that the string at index=0 should not be added to this space. In any case, you still need to use this for loop and do something for the spaces.

Then I remembered that I had seen the.join() method before, and it struck me that maybe this was the time I needed to use it!

It was solved so easily! One line of code can do all the work. Since the.join() method is called by the string object that will be used to join each string in the list, you don't have to worry about the opening spaces.

But that's not the only reason we need to use join() instead of the "+" method.

The logic behind the join() method

Let's compare the performance of these two methods, using Jupyter Notebook's magic method %timeit to evaluate them.

The performance shown above is based on 100,000 paths, and the results are very believable and obvious. Using the join() method can be 4 times faster than using "+" to join strings in a list.

Why is that? Take a look at the conceptual diagram I've drawn to demonstrate how strings can be concatenated using "+":

String concatenation using the "+" operator and the for loop

This shows what the for loop and the "+" operator do:

For each loop, the string can be found in the list

For each loop, executing the program will require requesting memory addresses twice, once for spaces and once for strings.

Python executors interpret the expression result +=''+s and request memory addresses for spaces.

Then, the executor realizes that spaces need to be concatenated with strings, so it will request memory addresses for the string s, which is the first loop "life."

There are also 12 memory allocations.

So what happens with join()?

Join strings to a list using the " join()" method

The executor calculates how many strings are in the list. There are six here.

This means that the string used to connect the list needs to be repeated 6-1 =5 times.

A total of 11 memory spaces are required, so all of them will be applied immediately and pre-allocated.

Then arrange the strings in order and return to the results page.

Obviously, the main difference is the number of memory allocations, which is the main reason for the performance improvement. Imagine joining six strings together using the join() method, which is already four times faster. What if we concatenate a lot of strings? It will change even more!

When concatenating strings in Python, obviously, the join() method is preferred for its performance.

Learning a programming language usually takes a long time. However, Python takes a relatively short time for beginners to learn, which is one of its advantages. But we shouldn't stop there and settle for what we can do with Python now.

At this point, I believe that everyone has a deeper understanding of "why not use + to connect strings in Python", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

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

Development

Wechat

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

12
Report