Python3 maketrans() Method
Description
The maketrans() method creates a character mapping translation table. In the simplest call, which takes two arguments, the first argument is a string containing the characters to be translated and the second is a string containing the translation targets.
The two strings must have the same length, in a one-to-one correspondence.
**Note:** Python3.4 no longer has string.maketrans(); it has been replaced by the built-in functions bytearray.maketrans(), bytes.maketrans(), and str.maketrans().
Syntax
Syntax of the maketrans() method:
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 the corresponding mapping characters.
- z -- optional, the characters to be deleted.
Return Value
Returns the new string generated after the translation.
Example
The following example demonstrates using the maketrans() method to convert all vowels into specified digits:
Example
#!/usr/bin/python3
Replace the letter R with N
txt
=
"Runoob!"
mytable
=
txt.
maketrans
(
"R"
,
"N"
)
(
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!!!"
(
str
.
translate
(
trantab
)
)
The output of the above example is:
Nunoob!
th3s 3s str3ng 2x1mpl2....w4w!!!
Set the parameter for characters to be deleted:
Example
#!/usr/bin/python3
txt
=
"Google Runoob Taobao!"
x
=
"mSa"
y
=
"eJo"
z
=
"odnght"
Set the characters to be deleted
mytable
=
txt.
maketrans
(
x
,
y
,
z
)
(
txt.
translate
(
mytable
)
)
The output of the above example is:
Gle Rub Tobo!
Python3 Strings