In Python, the maketrans()
method is a built-in method for strings that creates a translation table. This table is used by other string methods like translate()
to perform replacements or remove characters in a string.
The maketrans()
method is usually used in combination with the translate()
method to perform efficient and multiple character replacements in a string.
Here's the syntax of the maketrans()
method:
str.maketrans(x, y, z)
x
: If only one argument is passed, it must be a dictionary that contains the mapping of Unicode ordinals to their translations. If two strings are given, it will create a translation table where each character in the first string is mapped to the character at the same position in the second string.y
: Optional. If specified, it should be a string containing characters to be removed from the input string.z
: Optional. If specified, it should be a string with characters to be mapped to None.maketrans()
method returns a translation table as a dictionary.Here's an example of using maketrans()
and translate()
to remove specific characters from a string:
# Creating the translation table to remove 'aeiou' from the string
trans_table = str.maketrans('', '', 'aeiou')
# Input string
input_string = "Hello, how are you today?"
# Removing 'aeiou' using translate() and the translation table
result_string = input_string.translate(trans_table)
print(result_string) # Output: "Hll, hw r y tdy?"
In this example, we created a translation table that maps 'a', 'e', 'i', 'o', and 'u' to None, effectively removing them from the input string. The resultant string, stored in result_string
, is printed as the output.