Python String translate() Method
The translate()
method is used to replace characters in a string based on a translation table created using str.maketrans()
method.
Syntax
str.translate(table)
Parameters
table
: This is a translation table created using the str.maketrans()
method that defines how to perform the character replacements.
Return Value
Returns a new string with characters replaced according to the translation table.
How It Works
1. First, you create a translation table using the str.maketrans()
method.
2. Then you apply this table to your string using the translate()
method.
Examples
Replacing Characters in a String
text = "abcde"
# Create a translation table
trans_table = str.maketrans("abc", "123")
# Translate the string
trans_text = text.translate(trans_table)
print(trans_text) # Output: 123de
Removing Characters from a String
You can remove specific characters from a string by providing them in the third parameter of the str.maketrans()
method.
text = "abcde"
trans_table = str.maketrans("", "", "aeiou")
trans_text = text.translate(trans_table)
print(trans_text) # Output: bcd
Using a Dictionary for Custom Mappings
You can pass a dictionary to str.maketrans()
to define custom character replacements. 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).
text = "abcde"
trans_table = str.maketrans({"a": "x", "b": "y", "c": "z", "d": None})
trans_text = text.translate(trans_table)
print(trans_text) # Output: xyze