Replace the row elements by the dictionary



  • Hello, please help with the task. There's a line.

    st = 'qwqewqewqeggghhhvvvvbvc'
    

    There's a dictionary.

    x = {a:3, d:5, g:8}
    

    The row shall be checked for the presence of symbols equal to the keys of the dictionary and, if any, replace the symbol in the row with the value in the dictionary. Something.

    for i in st:
       if x.keys() in st:
    

    I just don't know how to write. If x.keys() in stThen... ♪

    Thank you.



  • from string import maketrans
    
    def replace_text(text, valc):
        """
        >>> text = 'abcdefg'
        >>> valc = {'a': 1, 'g': 2}
        >>> print replace_text(text, valc)
        1bcdef2
        """
        frm = ''.join([str(i) for i in valc.keys()])
        to = ''.join([str(i) for i in valc.values()])
        trantab = maketrans(frm, to)
        return text.translate(trantab)
    
    if __name__ == '__main__':
        import doctest
        doctest.testmod()
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2