Python String connection method analysis

Source: Internet
Author: User
This paper analyzes the Python string connection method. Share to everyone for your reference, as follows:

Python string Connection There are several methods, the list that everyone may use, the first method is the lowest efficiency, and also to introduce the following 2 kinds of high-efficiency methods, we hope to help.

First introduced lower efficiency, some novice friends will make this mistake:

A = [' A ', ' B ', ' C ', ' d ']content = ' For i in a:  content = content + iprint content

Why is efficiency low?

Cause: In the loop connection string, he once each connection, will re-open space, and then connect the string, then put in new space, once again cycle, but also open up new space, the string connected to put into the new space, so repeated, memory operations more frequent, each time to calculate memory space, Then open up memory space, and then free up memory space, the efficiency is very low, you may be less than the operation of the data can not be seen, the feeling of little impact, but you encounter more than the amount of operation data, this method will retire.

Or take a look at the following 2 more advanced methods to put.

Method 1: Use the string Join method:

A = [' A ', ' B ', ' C ', ' d ']content = ' content = '. Join (a) print content

Method 2: Replace the placeholder with a string

A = [' A ', ' B ', ' C ', ' d ']content = ' content = '%s%s%s%s '% tuple (a) print content

More readers interested in Python related content can view this site topic: "Introduction to Python and Advanced Classic Tutorial" and "Python file and directory Operations Tips Summary"

I hope this article is helpful for Python program design.

  • 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.