Replace characters in string from dictionary mapping
15,618
Solution 1
Translations are way faster.
>>> import string
>>> text.translate(string.maketrans("".join(restAlphaSet),"".join(item)))
Solution 2
You are overlooking the translate function. See here for a usage example.
Author by
NickG
Updated on June 23, 2022Comments
-
NickG almost 2 years
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,list(item)))
where restAlphaSet it a string and list(item) is list converted iteration
I am trying to use this to replace all the characters in my string. I found a replaceAll function online that looks like the following:
def replace_all(text, dic): for i, j in dic.iteritems(): if i != j: text = text.replace(i, j) return text
Unfortunately, this is flawed as if the mapping has a->b, b->a, then nothing would get changed as the b's would be changed back to the a's.
I found the translate function, but it doesn't accept a dictionary input.
-
cfedermann about 12 yearsWhat about removing the
b -> a
mappings? -
Joel Cornett about 12 yearsThere's a syntax error in your example function.
If i!=j
needs a colon at the end, else it will generate a SyntaxError. -
Lev Levitsky about 12 yearsFirst it will fail with
IndentationError
:) -
NickG about 12 yearsits very similar to a cryptogram. So letters can be mapped to any other letter (no dupliactes), I just need an order independent function. And ya I copied bad, i'll add colon
-
georg about 12 years
translate
does accept dicts if applied to unicode objects (see docs.python.org/library/stdtypes.html#str.translate) -
Gareth Latty about 12 yearsWho cares if translate accepts
dict
s? You made adict
because that was what you needed, if you don't, just use your lists to construct a translation table.
-
-
NickG about 12 yearsit seems the translate function has the same issue as before where it is changing characters back to what they were.
-
luke14free about 12 years@NickG mm.. it must be an issue with your code, post it so that we can figure out what's the problem.
-
mirek over 3 yearsPy 3.x?, sure 3.9+: str.maketrans (no need to import).
-
mirek over 3 yearsstr.maketrans (don't import: string)