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
I don't know about speed but this is my workaday quick fix:
... but I like the #1 regex answer above. Note - if one new value is a substring of another one then the operation is not commutative.
Here my $0.02. It is based on Andrew Clark's answer, just a little bit clearer, and it also covers the case when a string to replace is a substring of another string to replace (longer string wins)
It is in this this gist, feel free to modify it if you have any proposal.
I needed a solution where the strings to be replaced can be a regular expressions, for example to help in normalizing a long text by replacing multiple whitespace characters with a single one. Building on a chain of answers from others, including MiniQuark and mmj, this is what I came up with:
It works for the examples given in other answers, for example:
The main thing for me is that you can use regular expressions as well, for example to replace whole words only, or to normalize white space:
If you want to use the dictionary keys as normal strings, you can escape those before calling multiple_replace using e.g. this function:
The following function can help in finding erroneous regular expressions among your dictionary keys (since the error message from multiple_replace isn't very telling):
Note that it does not chain the replacements, instead performs them simultaneously. This makes it more efficient without constraining what it can do. To mimic the effect of chaining, you may just need to add more string-replacement pairs and ensure the expected ordering of the pairs:
I built this upon F.J.s excellent answer:
One shot usage:
Note that since replacement is done in just one pass, "café" changes to "tea", but it does not change back to "café".
If you need to do the same replacement many times, you can create a replacement function easily:
Improvements:
Enjoy! :-)
Another example : Input list
The desired output would be
Code :
Here is another way of doing it with a dictionary: