Python String maketrans() Method
The maketrans()
method is used to create a translation table that can be used with the translate()
method to replace or remove specified characters in a string.
Syntax
str.maketrans(x, y, z)
Parameters
x
(required): This can be a string or a dictionary. If it is a string, it should contain characters that you want to replace. If it is a dictionary, it must be the only parameter passed. In this case, the keys should be the characters (or their Unicode ordinals) to be replaced, and the values should be the replacement characters (or None
for deletion).
y
(optional): Used only if x
is a string. It must be the same length as x
. Each character in x
will be replaced by the corresponding character in y
.
z
(optional): String of characters to be deleted.
Return Value
Returns a translation table (a dictionary) that can be used with the translate()
method.
Examples
Replace Characters in a String
text = "abcde"
trans_table = str.maketrans("abc", "123")
translated_string = text.translate(trans_table)
print(translated_string) # Output: 123de
Remove Characters from a String
You can remove characters from a string by providing them in the third parameter of the maketrans()
method.
text = "abcde"
# Create a translation table to delete vowels
trans_table = str.maketrans("", "", "aeiou")
translated_string = text.translate(trans_table)
print(translated_string) # Output: bcd
Using a Dictionary for Custom Mappings
text = "abcd"
trans_table = str.maketrans({"a": "x", "b": "y", "c": None})
translated_string = text.translate(trans_table)
print(translated_string) # Output: xyd