Why does 'a'.translate({'a':'b'}) return 'a' instead of 'b'? I'm using Python 3.
            Asked
            
        
        
            Active
            
        
            Viewed 3.1k times
        
    33
            
            
         
    
    
        Ashwini Chaudhary
        
- 244,495
- 58
- 464
- 504
 
    
    
        fhucho
        
- 34,062
- 40
- 136
- 186
1 Answers
61
            
            
        The keys used are the ordinals of the characters, not the characters themselves:
'a'.translate({ord('a'): 'b'})
It's easier to use str.maketrans
>>> 'a'.translate(str.maketrans('a', 'b'))
'b'
>>> help(str.translate)
Help on method_descriptor:
translate(...)
    S.translate(table) -> str
    Return a copy of the string S, where all characters have been mapped
    through the given translation table, which must be a mapping of
    Unicode ordinals to Unicode ordinals, strings, or None.
    Unmapped characters are left untouched. Characters mapped to None
    are deleted.
- 
                    3Only the key needs to be an ordinal (http://docs.python.org/3/library/stdtypes.html#str.translate) – Volatility Jun 10 '13 at 09:29
- 
                    :( Did I just miss out when jamylak posted maketrans? – TerryA Jun 10 '13 at 09:30
- 
                    Get this to work with examples from [Remove specific characters from a string in python](http://stackoverflow.com/a/3939381/3491991) – zelusp Nov 08 '16 at 23:49
 
    