Python substitution string substitution steps

Time:2019-10-7

It is impossible to modify the string itself, because the string is an immutable type and can only be produced by some means. Then assign the copy to the original string to achieve a similar replacement effect. Several methods are introduced here.

Replace old strings with new ones: use str. replace (old, new, max)

1) When a string calls this function, a copy of the string is generated. New will replace old in the copy.

2) old – the original substring.

3) new-new substring, used to replace old.

4) max – the maximum number of substitutions (not specified, all substitutions)

When Max is specified, if the number of old substrings is exceeded, all substitutions are made.

1. Select and reconnect after segmentation:

Split string: str. split (sep = None, maxsplit = – 1)

1) String calls split function to return a list of separate substrings.

2) SEP specifies the delimiter and returns a list if not specified.

3) The delimiter can be multiple characters.

The specified delimiter should be included in the string, and after partitioning, the delimiter disappears.

(Note if the split is in the string, it is equivalent to sep = None)

Maxsplit, used to specify the number of partitions, so the list will have maxsplit + 1 elements at most.  

If maxsplit is not specified or – 1, the number of splits is not limited and all possible splits are performed.

4. Continuous delimiters are not grouped together but are considered to separate empty strings.

String connection: str. join (iterable)

The parameter terable is an iterative object whose elements must be strings (for example, all strings in a list).

A string calling the join function returns a large string with these elements.

The caller will act as a separator between elements. (Callers can be empty, blank, or any other string)

Split function and join function are used together to achieve the purpose of screening and replacement.