Three methods for merging strings in Python

Source: Internet
Author: User
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.

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.