Python string Method - translate()

https:/‮w/‬ww.theitroad.com

The translate() method is a built-in string method in Python that returns a copy of a string where certain characters are replaced with the character(s) specified in a translation table.

The syntax for using translate() method is as follows:

string.translate(table)

Here, string is the original string, and table is a translation table, which is a dictionary that maps each character to its replacement.

The method returns a new string where each character in the original string is replaced with the corresponding character(s) in the translation table.

Here's an example of using the translate() method:

string = "Hello, World!"
table = str.maketrans("lo", "12")
translated_string = string.translate(table)
print(translated_string)

Output:

He22, W12rld!

In the example above, the translate() method was used to replace each occurrence of the characters "l" and "o" in the original string "Hello, World!" with the characters "1" and "2", respectively. The translation table was created using the str.maketrans() method, which returns a translation table based on two strings that specify the characters to replace and their replacements. The resulting translated string is stored in the variable translated_string. Note that the original string is not modified by the translate() method.