Python String maketrans() Method

The maketrans() method is a string method that returns a mapping table that can be used with the translate() method to replace specified characters. The maketrans() method can take one or two arguments. If one argument is given, it must be a dictionary mapping characters to characters. If two arguments are given, they must be strings of equal length, and each character in the first string will be mapped to the corresponding character in the second string. Optionally, a third argument can be given as a string of characters that will be removed from the original string.

Here are some examples of using the maketrans() method:

# example 1: create a mapping table using a dictionary
txt = "Hello Sam!"
mydict = {"H": "J", "S": "P"}
mytable = str.maketrans(mydict)
print(txt.translate(mytable))
# Jello Pam!

# example 2: create a mapping table using two strings
txt = "Hi Sam!"
x = "mSa"
y = "eJo"
mytable = str.maketrans(x, y)
print(txt.translate(mytable))
# He Joe!

# example 3: create a mapping table with a third argument
txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
mytable = str.maketrans(x, y, z)
print(txt.translate(mytable))
# G i Joe!

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions