Python str.maketrans() function
In Python, the str.maketrans()
method is used to create a translation table that maps characters to their replacements for use with the str.translate()
method. This method provides a convenient way to define a set of character substitutions, deletions, or transformations in a string.
Syntax
- x: A string containing characters to be replaced.
- y (optional): A string containing characters that will replace the corresponding characters in
x
. If provided,y
must be of the same length asx
. - z (optional): A string containing characters to be deleted from the string when using
translate()
.
How It Works
- Mapping Characters:
When you pass two strings x
and y
to maketrans()
, it creates a mapping where each character in x
is replaced by the corresponding character in y
.
- Deleting Characters:
If you provide a string z
, it indicates which characters should be removed from the original string when translating.
Example Usage
- Basic Character Mapping:
In this example, 'a', 'b', and 'c' are replaced by '1', '2', and '3', respectively.
- Using Deletion:
You can also specify characters to delete:
Here, the vowels 'a', 'e', 'i', 'o', and 'u' are removed from the string.
- Multiple Character Substitutions and Deletions:
You can combine mappings and deletions:
In this case, 'a', 'b', and 'c' are replaced with 'x', 'y', and 'z', while 'e' is deleted from the string.
- Using Unicode Characters:
You can also use Unicode characters in the translation table:
Summary
- Use
str.maketrans()
to create a translation table for character replacements and deletions. - It allows you to define mappings between characters easily and efficiently.
- The created translation table can be used with
str.translate()
to manipulate strings, making it useful for various text processing tasks. - This method is versatile and can handle character substitutions, removals, and transformations, making it a powerful tool in string manipulation.