Replace Characters In String From Dictionary Mapping
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: dictionary = dict(zip(restAlphaSet
Solution 1:
Translations are way faster.
>>>import string>>>text.translate(string.maketrans("".join(restAlphaSet),"".join(item)))
Solution 2:
Solution 3:
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 =""forchar in text:
for i, j in dic.iteritems():
ifchar == i:
new_text += j
return new_text
Post a Comment for "Replace Characters In String From Dictionary Mapping"