Home >Backend Development >Python Tutorial >Two examples of using join in Python are shared

Two examples of using join in Python are shared

零下一度
零下一度Original
2017-07-26 09:48:101904browse

Python uses two instances of join to share

a1 = {: , : , : , : = open(,,encoding= key ===  +

If you want to merge (list, tuple, dictionary, file, set or generator, etc. ) string is a sequence or iterable, the fastest way is to use the join() method

[python] view plain copy
>>> a = ["hello", "world"]  
>>> a  
['hello', 'world']  
>>> ' '.join(a)  
'hello world'  
>>> ','.join(a)  
'hello,world'  
>>> ''.join(a)  
'helloworld'

If you want to merge (list, tuple, dictionary, file, collection or generator, etc.) If the string is a sequence or iterable, the fastest way is to use the join() method

[python] view plain copy
>>> a = ["hello", "world"]  
>>> a  
['hello', 'world']  
>>> ' '.join(a)  
'hello world'  
>>> ','.join(a)  
'hello,world'  
>>> ''.join(a)  
'helloworld'

Usually when formatting strings, improper selection can cause serious problems to the application. Performance loss, when we use the plus (+) operator to concatenate a large number of strings, it is very inefficient, because the plus sign connection will cause memory copying and garbage collection operations. Each time the += operation is performed, a new string object is created. You're better off collecting all the string fragments first and then concatenating them.


Conclusion: When to use (+) and when to use join, you should decide which solution to use based on the characteristics of your application






The above is the detailed content of Two examples of using join in Python are shared. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn