I would like to use the .replace function to replace multiple strings.
I currently have
string.replace("condition1", "")
but would like to have something like
string.replace("condition1", "").replace("condition2", "text")
although that does not feel like good syntax
what is the proper way to do this? kind of like how in grep/regex you can do \1
and \2
to replace fields to certain search strings
Why not one solution like this?
This is just a more concise recap of F.J and MiniQuark great answers. All you need to achieve multiple simultaneous string replacements is the following function:
Usage:
If you wish, you can make your own dedicated replacement functions starting from this simpler one.
I would like to propose the usage of string templates. Just place the string to be replaced in a dictionary and all is set! Example from docs.python.org
You should really not do it this way, but I just find it way too cool:
Now,
answer
is the result of all the replacements in turnagain, this is very hacky and is not something that you should be using regularly. But it's just nice to know that you can do something like this if you ever need to.
Here's a sample which is more efficient on long strings with many small replacements.
The point is in avoiding many concatenations of long strings. We chop the source string to fragments, replacing some of the fragments as we form the list, and then join the whole thing back into a string.
Here is a short example that should do the trick with regular expressions:
For example: