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
You could just make a nice little looping function.
where
text
is the complete string anddic
is a dictionary — each definition is a string that will replace a match to the term.Note: in Python 3,
iteritems()
has been replaced withitems()
Careful: Python dictionaries don't have a reliable order for iteration. This solution only solves your problem if:
For instance:
Possible output #1:
Possible output #2
One possible fix is to use an OrderedDict.
Output:
Careful #2: Inefficient if your
text
string is too big or there are many pairs in the dictionary.Here is a variant of the first solution using reduce, in case you like being functional. :)
martineau's even better version:
Or just for a fast hack:
this is my solution to the problem. I used it in a chatbot to replace the different words at once.
this will become
The cat hunts the dog
In my case, I needed a simple replacing of unique keys with names, so I thought this up:
Starting from the precious answer of Andrew i developed a script that loads the dictionary from a file and elaborates all the files on the opened folder to do the replacements. The script loads the mappings from an external file in which you can set the separator. I'm a beginner but i found this script very useful when doing multiple substitutions in multiple files. It loaded a dictionary with more than 1000 entries in seconds. It is not elegant but it worked for me