Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

python text Stitch or merge strings


May 10, 2021 Python2


Table of contents


python text Stitch, merge strings

Scene:

Stitch and merge strings

In this scenario, of course, the first thing that comes to mind is to connect the two strings using either . . . or .

  >>> a='a'  
  >>> b='b'  
  >>> c=a+b  
  >>> c  
  'ab'  
  >>>   

If the entire program has only two strings to stitch, that's no problem

But if there is a lot of stitching in the program, or even the need for circular stitching, this time performance problems will occur

Why: Strings cannot be modified in place, changing a string is creating a new string instead of the old one, and if you have N strings that need to be changed, you create N strings, then discard N old strings, allocate a large string space, and fill the string for approximately as long as this string

Therefore, we recommend using the .join method, and if some strings are not in place in the first place, you can use list staging, and then join

For example:


  >>> a='a'  
  >>> b='b'  
  >>> c=a.join (b)  
  >>> c  
  'b'  
  >>>