Python3 maketrans() Method
Description
The maketrans() method is used to create a character mapping translation table. In the simplest call form 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 conversion target.
The two strings must be of the same length, forming a one-to-one correspondence.
Note:Python 3.4 no longer has string.maketrans(); it has been replaced by the built-in function: bytearray.maketrans()、bytes.maketrans()、str.maketrans() 。
Syntax
maketrans() method syntax:
string.maketrans(x[, y[, z]])
Parameters
- x -- Required, a string consisting of the characters to be replaced in the string.
- y -- Optional, a string of corresponding mapping characters.
- z -- Optional, characters to be deleted.
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
# Replace the letter R with N
txt = "Example!"
mytable = txt.maketrans("R", "N")
print(txt.translate(mytable))
# Use strings to set the characters to be replaced, in one-to-one correspondence
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print (str.translate(trantab))
The output of the above example is as follows:
Nunoob! th3s 3s str3ng 2x1mpl2....w4w!!!
Set the character parameter to be deleted:
Example
txt = "Google Example Taobao!"
x = "mSa"
y = "eJo"
z = "odnght" # Set the characters to delete
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))
The output of the above example is as follows:
Gle Rub Tobo!
Other Extensions
Python3 Strings