Python maketrans() Method
Description
The Python maketrans() method is used to create a conversion table for character mapping. For the simplest call that accepts two parameters, the first parameter is a string representing the characters to be converted, and the second parameter is also a string representing the target of conversion.
Note:The two strings must be of the same length, with a one-to-one correspondence.
Syntax
maketrans() method syntax:
str.maketrans(intab, outtab)
Parameters
- intab -- the string of characters to be replaced in the string.
- outtab -- the string of corresponding mapped characters.
Return Value
Returns a new string generated after the string conversion.
Example
The following example demonstrates using the maketrans() method to convert all vowel letters to specified digits:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from string import maketrans # The maketrans function must be called.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
# -*- coding: UTF-8 -*-
from string import maketrans # The maketrans function must be called.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
The output of the above example is shown below:
th3s 3s str3ng 2x1mpl2....w4w!!!
Other Extensions
Python Strings