![]() |
VOOZH | about |
Python translate() method is used to transform a string by replacing or removing specific characters based on a translation table. This table is created using the str.maketrans() method. It’s ideal for scenarios where we need to:
Example:
In the given example, we are using str.translate() method is used to translate a string by specifying a mapping using ASCII values.
h2ll4 w4rld
Let's explore python string translate() method in detail:
str.translate(table)
Parameters:
Returns:
The maketrans() method is a built-in string method in Python that generates a translation table. It is primarily used in conjunction with the translate() method to perform character-by-character translations or deletions.
Syntax: maketrans(str1, str2, str3)
Parameters:
- str1: Specifies the list of characters that need to be replaced.
- str2: Specifies the list of characters with which the characters need to be replaced.
- str3: Specifies the list of characters that need to be deleted.
Returns: Returns the translation table which specifies the conversions that can be used by translate()
We can use translate() to remove unwanted characters, like punctuation. Removing punctuation from a string is a common task, especially in text preprocessing for Natural Language Processing (NLP) or data cleaning.
Example:
Hello World Welcome to Python
Explanation:
Replace multiple characters in a string using a custom mapping. In this example, we demonstrate how to map specific characters to others for custom transformations.
Example:
Th*s_*s_*n_*x*mpl*.
Explanation:
Let’s build a basic substitution cipher using the translate() method. This is often used in simple encryption or encoding scenarios.
Example:
Encoded: uvwxy zg Decoded: abcde fg
Explanation:
Let’s combine character removal and replacement for a more complex text-processing task.
Example:
pYthn. is awesme!
Explanation: