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.

Share:
15,618
NickG
Author by

NickG

Updated on June 23, 2022

Comments

  • NickG
    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
      cfedermann about 12 years
      What about removing the b -> a mappings?
    • Joel Cornett
      Joel Cornett about 12 years
      There'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
      Lev Levitsky about 12 years
      First it will fail with IndentationError :)
    • NickG
      NickG about 12 years
      its 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
      georg about 12 years
      translate does accept dicts if applied to unicode objects (see docs.python.org/library/stdtypes.html#str.translate)
    • Gareth Latty
      Gareth Latty about 12 years
      Who cares if translate accepts dicts? You made a dict because that was what you needed, if you don't, just use your lists to construct a translation table.
  • NickG
    NickG about 12 years
    it seems the translate function has the same issue as before where it is changing characters back to what they were.
  • luke14free
    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
    mirek over 3 years
    Py 3.x?, sure 3.9+: str.maketrans (no need to import).
  • mirek
    mirek over 3 years
    str.maketrans (don't import: string)