Translate() and maketrans() methods of string in Python

Explained

use translate to replace specific characters in a string, such as 12345 for aeiou. Using translate requires the maketrans method to build the replacement table
note: python2’s maketrans method needs to be imported, whereas python3 is built in. In python3, using the syntax of python2 to import: ImportError: cannot import name ‘maketrans’

str.maketrans()

python document interpretation

Help on built-in function maketrans in str:

str.maketrans = maketrans(...)
    Return a translation table usable for str.translate().

    If there is only one argument, it must be a dictionary mapping Unicode
    ordinals (integers) or characters to Unicode ordinals, strings or None.
    Character keys will be then converted to ordinals.
    If there are two arguments, they must be strings of equal length, and
    in the resulting dictionary, each character in x will be mapped to the
    character at the same position in y. If there is a third argument, it
    must be a string, whose characters will be mapped to None in the result.

str.translate()

python document interpretation

Help on method_descriptor in str:

str.translate = translate(self, table, /)
    Replace each character in the string using the given translation table.
    
      table
        Translation table, which must be a mapping of Unicode ordinals to
        Unicode ordinals, strings, or None.
        
The table must implement lookup/indexing via __getitem__, for instance a
    dictionary or list.  If this operation raises LookupError, the character is
    left untouched.  Characters mapped to None are deleted.

Example

replace aeiou with 12345


trantab = str.maketrans("aeiou", "12345")

print ("EXAMPLE:aeiou".translate(trantab))

Output

is

EXAMPLE:12345

Read More: