I\'m pretty new to python, so forgive me if I am missing an obvious built-in function.
I have a dictionary mapping I generated like the following:
di
You are overlooking the translate function. See here for a usage example.
Translations are way faster.
>>> import string
>>> text.translate(string.maketrans("".join(restAlphaSet),"".join(item)))
I realize it is an old question, however it seems there was no answer using dictionary with mapping for both a->b
and b->a
.
I needed a similar function, and the trick that did a job was to first iterate over the string in which we need replacement and then for each char to look for a mapping.
def replace_all(text, dic):
new_text = ""
for char in text:
for i, j in dic.iteritems():
if char == i:
new_text += j
return new_text