3 methods for merging strings in Python and 3 methods for merging strings in python
Purpose
Merge some small strings into a large string, more consideration is the performance
Method
There are several common methods:
1. Use the + = Operator
Copy codeThe 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.
Copy codeThe Code is as follows:
BigString =''
For e in pieces:
BigString + = e +''
Or use
Copy codeThe Code is as follows:
Import operator
BigString = reduce (operator. add, pieces ,'')
2. Use the % Operator
Copy codeThe 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
Copy codeThe 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.