This article mainly introduces three methods for merging strings in Python. This article explains how to use the + operator, the % operator, and the String
Purpose
Merge some small strings into a large string, more consideration is the performance
Method
There are several common methods:
1. use the + = operator
The code is as follows:
BigString = small1 + small2 + small3 +... + smalln
For example, if there is a segment pieces = ['Today', 'is', 'really ', 'A', 'good', 'day'], we want to link it.
The code is as follows:
BigString =''
For e in pieces:
BigString + = e +''
Or use
The code is as follows:
Import operator
BigString = reduce (operator. add, pieces ,'')
2. use the % operator
The code is as follows:
In [33]: print '% s, Your current money is %. 1f' % ('upta', 500.52)
Nupta, Your current money is 500.5
3. use the ''. join () method of String
The code is as follows:
In [34]: ''. join (pieces)
Out [34]: 'Today is really a good day'
Performance
A few strings need to be spliced. try to use the % operator to keep the code readable.
A large number of strings need to be concatenated. the '. join method is used, which only copies one pieces, without generating intermediate results between subkeys.