Replace characters in string from dictionary mapping

前端 未结 3 737
深忆病人
深忆病人 2020-12-11 13:08

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         


        
相关标签:
3条回答
  • 2020-12-11 13:42

    You are overlooking the translate function. See here for a usage example.

    0 讨论(0)
  • 2020-12-11 13:44

    Translations are way faster.

    >>> import string
    >>> text.translate(string.maketrans("".join(restAlphaSet),"".join(item)))
    
    0 讨论(0)
  • 2020-12-11 13:47

    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
    
    0 讨论(0)
提交回复
热议问题