Easy Tutorial
❮ Python Mongodb Query Document Python Os Stat_Float_Times ❯

Python3 maketrans() Method

Python3 Strings


Description

The maketrans() method is used to create a translation table for character mapping. For the simplest call with two arguments, the first argument is a string representing the characters to be converted, and the second argument is a string representing the target characters for conversion.

Both strings must have the same length, establishing a one-to-one relationship.

Note: Python3.4 no longer has string.maketrans(). Instead, built-in functions are used: bytearray.maketrans(), bytes.maketrans(), str.maketrans().

Syntax

Syntax for the maketrans() method:

string.maketrans(x[, y[, z]])

Parameters

Return Value

Returns a new string generated after conversion.

Example

The following example demonstrates using the maketrans() method to convert all vowel letters to specified numbers:

#!/usr/bin/python3

# Replace letter R with N
txt = "tutorialpro!"
mytable = txt.maketrans("R", "N")
print(txt.translate(mytable))

# Set characters to be replaced, one-to-one
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))

Output of the above example:

Nunoob!
th3s 3s str3ng 2x1mpl2....w4w!!!

Setting the characters to be removed:

#!/usr/bin/python3

txt = "Google tutorialpro Taobao!"
x = "mSa"
y = "eJo"
z = "odnght"   # Set characters to be removed
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))

Output of the above example:

Gle Rub Tobo!

Python3 Strings

❮ Python Mongodb Query Document Python Os Stat_Float_Times ❯