Python String translate() Method

The Python translate() method is used to return a string where each character is mapped to its corresponding character as per a translation table. It returns a new string with the translated characters.

To use translate(), you need to first create a translation table using the maketrans() method. The maketrans() method takes two parameters: a string of characters that need to be replaced, and a string of characters that will replace them.

For example:

text = "Hello Sam!"
# create a translation table that replaces "S" with "P"
table = text.maketrans("S", "P")
# apply the translation table on the text
result = text.translate(table)
print(result)

# Output: Hello Pam!

You can also use translate() to delete certain characters from a string by passing a third parameter to the maketrans() method. The third parameter is a string of characters that will be removed from the original string.

For example:

text = "Hello Sam!"
# create a translation table that deletes "a" and "m"
table = text.maketrans("", "", "am")
# apply the translation table on the text
result = text.translate(table)
print(result)

# Output: Hello S!

If you have any questions about this code, you can drop a line in comment.

 

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions