Module for multiple runs of the .replace string method
Do you need to replace a substring with another one multiple times on the same string?
Do you do that frequently and which there was a nicer way to write it?
This module might be for you
Basic Usage
It takes in a string, and 2 lists. Each item in the first list will be replaced by the corresponding item in the second list.
For example, the below:
|
|
Would be replaced with:
|
|
This might not seem like a saver at first but there are a few use cases where it could come in handy.
If the replacements being made are created at runtime (especially the number of replacements being done on a string) then you don’t need to hardcode long chains of .replace() functions.
The formatMode parameter
Another advantage of the mreplace function, if the default behaviour:
The formatMode
parameter allows switching between an ‘all-at-once’ or ‘one-by-one’ replacement mode.
When using chains of .replace() functions (analogous to ‘one-by-one’ mode) if you have a replacement from “A” to “B” and later in the chain have a replacement of “B” to “C”, then all “A"s and all “B"s will be changed to “C”, which might not be desireable.
Or perhaps you want to switch 2 sub-strings: take for example the string “E before I” and you need to switch the letters “E” and “I”. If you used a chain of .replace() functions then such as in the function:
|
|
you would end up with the string “E before E”.
The ‘all-at-once’ mode (when formatMode
is True) uses the .format() function to evaluate each replacement as though the previous ones didn’t happen, therefore the order is not important and swaps are possible.
Setting formatMode
to False means the mreplace function will run a loop of .replace() calls instead.
The Code
|
|