Python String maketrans()
Python String.maketrans() method creates a mapping table which can be used with the String.translate() method. Using this mapping table, translate() method replaces the characters with specified values.
In this tutorial, we will learn the syntax and examples for maketrans() method of String class.
Syntax
The syntax of String maketrans() method in Python is
str.maketrans(x, y, z)
where
Parameter | Required/ Optional | Description |
---|---|---|
x | Required | If only this parameter is specified, then it has to be a dictionary. If y or/and z parameter(s) is also specified, then this parameter has to be a string. |
y | Optional | A string whose length is same as that of x . |
z | Optional | A string. Specifies which characters are to be removed from the calling string. |
Examples
Replace a character with Other
In the following program, we take a string 'apple'
in x
, and replace 'p'
with 't'
using maketrans() method.
Example.py
x = "apple"
mapping = x.maketrans('p', 't')
result = x.translate(mapping)
print("Original String :", x)
print("Translated String :", result)
Output
Original String : apple
Translated String : attle
Replace Characters based on Mapping
In the following program, we take a string 'apple'
in x
, and replace 'p'
with 't'
, and 'e'
with 'm'
using maketrans() method.
Example.py
x = "apple"
mapping = x.maketrans({'p':'t', 'e': 'm'})
result = x.translate(mapping)
print("Original String :", x)
print("Translated String :", result)
Output
Original String : apple
Translated String : attlm
Replace Characters based on Mapping and Delete Some Characters
In the following program, we take a string 'apple'
in x
, and replace 'p'
with 't'
, 'e'
with 'm'
, and delete the characters 'abc'
using maketrans() method.
Example.py
x = "apple"
mapping = x.maketrans('pe', 'tm', 'abc')
result = x.translate(mapping)
print("Original String :", x)
print("Translated String :", result)
Output
Original String : apple
Translated String : ttlm
Conclusion
In this Python Tutorial, we learned how to create a mapping table for replacing and deleting characters in a string, using String method – maketrans().