Python string Method - maketrans()

The maketrans() method is a built-in string method in Python that returns a translation table that can be used with the translate() method to replace specific characters in a string.

Syntax:

str.maketrans(x[, y[, z]])
Source‮www:‬.theitroad.com

Here, x is a string of characters to replace, y is a string of corresponding characters to replace them with, and z is a string of characters to delete from the string. If only x is given, it must be a dictionary mapping Unicode ordinals to replacement strings.

Example:

string = "Hello World!"
translation_table = str.maketrans("HW", "hw")
print(string.translate(translation_table))

Output:

'hello world!'

In the above example, we create a translation table that maps 'H' to 'h' and 'W' to 'w' and then apply it to the string using the translate() method. The resulting string has all the 'H's and 'W's replaced with 'h's and 'w's, respectively.