Python 3 – String maketrans() Method
In Python programming language, we often need to manipulate string sequences. One common task is to translate characters from one sequence to another sequence. The maketrans()
method is a built-in method in Python 3, which provides an easy way to generate a translation table for such manipulation.
Syntax
maketrans(x[, y[, z]])
Parameters
x
: A string with one or more characters to be replaced.y
: A string with corresponding replacement characters (if any). If not provided, the characters in thex
string will be deleted.z
: A string with characters that need to be mapped toNone
.
Return value
The maketrans()
method returns a translation table that can be used with the translate()
method of a string object.
Example
Let’s see an example to understand how to use the maketrans()
method.
Example 1: Simple translation
# Create a translation table
table = str.maketrans("aeiou", "12345")
# Translate a string using the table
string = "Hello World"
print(string.translate(table)) # Output: H2ll4 W4rld
In the above example, we created a translation table using the maketrans()
method, which maps the vowels in the source string with the digits 1 to 5. Then we used the translate()
method of a string object to apply this translation to the given string.
Example 2: Mapping to None
# Create a translation table
table = str.maketrans("", "", "!@#%")
# Translate a string using the table
string = "Hello!@#%World"
print(string.translate(table)) # Output: HelloWorld
In the above example, we created a translation table using the maketrans()
method, which maps the characters ‘!@#$%’ in the source string to None
. This means that these characters will be deleted from the string. Then we used the translate()
method of a string object to apply this translation to the given string.
Conclusion
The maketrans()
method is a powerful tool for string manipulation in Python 3. It provides an easy way to generate a translation table that can be used with the translate()
method of a string object. With this method, you can easily replace, delete, or map characters in a string sequence. The maketrans()
method is very efficient, especially when you need to perform the same translation on multiple strings.