Definition
The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table.
Use the maketrans() method to create a mapping table.
If a character is not specified in the dictionary/table, the character will not be replaced.
If you use a dictionary, you must use ascii codes instead of characters.
Syntax
string.translate(table)
Parameters
Parameter | Description |
---|---|
table | Required. Either a dictionary, or a mapping table describing how to perform the replace |
Examples:
mydict = {83: 80}
testStr = "Welcome to the Python tutorials!"
print(testStr.translate(mydict))
# other examples
txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))