How to translate a python string according a given dictionary?

PythonServer Side ProgrammingProgramming

We can use the method translate() which returns a copy of the string in which all characters have been translated using table (constructed with the maketrans() function in the string module), optionally deleting all characters found in the string deletechars. 

 example

from string import maketrans   # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "This is a string example....wow!!!";
print str.translate(trantab)

Output

This will give us the output −

Th3s 3s 1 str3ng 2x1mpl2....w4w!!!
raja
Published on 12-Dec-2017 14:50:19
Advertisements