Python String maketrans() Method
The maketrans() method is used to create the conversion table for the character map. For the simplest call that accepts two arguments, the first argument is a string indicating the character to be converted, and the second argument is also a string indicating the target of the conversion.
The two strings must be of the same length, in a one-to-one correspondence.
Note: Python 3.4 no longer has string.maketrans(), instead, the built-in functions: bytearray.maketrans(), bytes.maketrans(), str.maketrans() .
Python String maketrans() Syntax
Syntax of maketrans() method.
string.maketrans(x[, y[, z]])
Python String maketrans() Parameters
Syntax of the maketrans() method.
- y – optional, the string of corresponding mapped characters.
- z – optional, the character to be deleted.
Python String maketrans() Return Value
Returns the new string generated after the string conversion.
Python String maketrans() Example#1
The following example shows the use of the maketrans() method to convert all vowel letters to the specified numbers.
#!/usr/bin/python3
# Replace the letter A with B
txt = "Apidemos!"
mytable = txt.maketrans("A", "B")
print(txt.translate(mytable))
# Use strings to set the characters to be replaced, one by one
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str1 = "this is string example for apidemos.com!!!"
print (str1.translate(trantab))
Output:
Python String maketrans() Example#2
Set the parameters for the character to be deleted.
#!/usr/bin/python3
txt = "Google ApiDemos Deepinout"
x = "mSa"
y = "eJo"
z = "odnght" # Set the character to be deleted
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))
Output: