Search code examples
pythonpython-2.7translate

Using translate in Python 2.7


I have a word with vowels like apple and want to replace the vowels with asterisks using translate. I am using Python 2.7.

I have created a translate table:

import string
table = string.maketrans('*****', 'aeiou')

But using it removes the vowels without replacing the vowel with asterisk:

>> 'apple'.translate(table, 'aeiou')
'ppl'

I already know that I can implement this using other methods like re:

import re
re.sub('[aeiou]', '*', 'Apple', flags=re.I)

But I want to know if there is a way using translate.


Solution

  • Sure, you need to give it a proper mapping that allows the __getitem__ method as per the docstring

    maps = {'a': '*', 'e': '*', 'o': '*', 'i': '*', 'u': '*'}
    
    table = str.maketrans(maps)
    
    'apple'.translate(table)
    
    '*ppl*'
    

    Since you now mention Python 2.7 solution it would be like this:

    import string
    
    table = string.maketrans('aeoiu', '*****')
    
    'apple'.translate(table)
    '*ppl*'