3 methods for merging strings in Python and 3 methods for merging strings in python

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.