Home > Article > Backend Development > Summarize 3 methods of merging strings in Python
This article mainly introduces 3 methods of Pythonmerging strings. This article explains the use of +=operator, the use of % operator, Use the ' '.join() method of String for 3 methods. Friends who need it can refer to the following
Purpose
Merging strings into one large string, more consideration is given to performance
Method
Common methods include the following:
1. Use the += operator
BigString=small1+small2+small3+...+smalln
For example, there is a fragment pieces=['Today','is','really' ,'a','good','day'], we want to connect it
BigString=' ' for e in pieces: BigString+=e+' '
or use
import operator BigString=reduce(operator.add,pieces,' ')
2. Use the % operator
In [33]: print '%s,Your current money is %.1f'%('Nupta',500.52) Nupta,Your current money is 500.5
3. Use String's ' '.join() method
In [34]: ' '.join(pieces) Out[34]: 'Today is really a good day'
About performance
There are a small number of strings that need to be spliced , try to use the % operator to keep the code readable
There are a large number of strings that need to be spliced, use the ''.join method, which only uses a copy of the pieces without creating an intermediate between the sub-items. result.
The above is the detailed content of Summarize 3 methods of merging strings in Python. For more information, please follow other related articles on the PHP Chinese website!