3 ways to combine strings in Python

Source: Internet
Author: User
Tags join in python

This article describes 3 ways to combine Python strings, and this article explains the use of the + + operator, using the% operator, and using String's '. Join () Method 3 methods, need friends can refer to the following

Objective

Combine some small strings into a large string, with more consideration for performance

Method

There are several common ways to do this:

1. Use the + = operator

The code is as follows:

Bigstring=small1+small2+small3+...+smalln

For example there is a fragment pieces=[' Today ', ' are ', ' really ', ' a ', ' good ', ' Day '], we want to link it up

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% operator

The code is as follows:

In [per]: print '%s,your current%.1f '% (' Nupta ', 500.52)

Nupta,your is 500.5

3. Use string's '. Join () method

The code is as follows:

In [%]: '. Join (Pieces)

OUT[34]: ' Is really a good day '

About Performance

A small number of strings need to be spliced to use the% operator to keep the code readable

There are a lot of strings that need stitching, using the '. Join method, which uses only one pieces copy without having to produce intermediate results between the 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.