Python string Join method efficiency comparison

Source: Internet
Author: User
Tags python string join

Method 1: Connect directly via the plus (+) operator
1 website =‘python‘ + ‘tab‘ +‘.com‘
Method 2:join Method
12 listStr =[‘python‘‘tab‘‘.com‘website =‘‘.join(listStr)
Method 3: Replace
1 website =‘%s%s%s‘ %(‘python‘‘tab‘‘.com‘)

The reason why Python uses + for string connections is inefficient because the strings in Python are immutable types, a new string is generated when using + to concatenate two strings, and a new string is required to re-request the memory, when the string of successive additions is many (a+b+c+d+ e+f+ ...) , inefficiency is inevitable.

Method 2 uses a slightly more complex, but high-efficiency connection to multiple characters, with only one memory request. And if the character of the list is connected, this method must be the preferred

In addition, when using string connection, note the different types of direct connection error conditions: Unicode and strings can be directly connected, strings and Chinese characters can be directly connected, but Unicode and Chinese characters can not be directly connected

Reference:

1, https://www.cnblogs.com/chenjingyi/p/5741901.html This blog conclusion There is a problem, the test method is still re-application of memory

Python string Join method efficiency comparison

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.