Python String translate() Function
The String translate()
method is used to replace specific characters in a string with other characters or remove them altogether. It requires a translation table that maps the characters to be replaced to their replacements.
The translation table can be generated using the maketrans()
static method.
## Syntax
```python
my_string.translate(table)
translate() Parameters
Python String translate()
function parameters:
Parameter | Condition | Description |
---|---|---|
table | Required | A translation table that maps the characters to be replaced to their replacements. |
translate() Return Value
Python String translate()
function returns a string where each character is mapped to its corresponding character as per the translation table.
Examples
Example 1: Replacing Characters with maketrans() and translate()
This example demonstrates how to use translate()
with a translation table generated by maketrans()
. It replaces vowels with digits in the string "tutorialreference".
text = 'tutorialreference'
table = str.maketrans('aeio', '4310')
translated_text = text.translate(table)
print(translated_text) # Output: tut0r14lr3f3r3nc3
output
tut0r14lr3f3r3nc3
Example 2: Removing Characters with maketrans() and translate()
This example shows how to use translate()
to remove characters from a string. It removes all vowels from "tutorialreference".
text = "tutorialreference"
vowels = "aeiouAEIOU"
table = str.maketrans("", "", vowels)
translated_text = text.translate(table)
print(translated_text) # Output: "ttrlrfrnc"
output
ttrlrfrnc
Example 3: Replacing Characters with ASCII Mapping with translate()
This example demonstrates replacing characters using an ASCII mapping table directly with translate()
method.
This replaces the t
, u
, r
characters with the corresponding uppercase letter.
text = "tutorialreference"
table = {116: 84, 117: 85, 114: 82}
print("The string before translating is: ", text)
print("The string after translating is: ", text.translate(table))
output
The string before translating is: tutorialreference
The string after translating is: TUToRialRefeRence
Example 4: Removing Punctuation with maketrans() and translate()
This example removes all punctuation from a string using translate()
and a translation table generated by maketrans()
.
import string
text = "https://tutorialreference.com"
table = str.maketrans("", "", string.punctuation)
translated_text = text.translate(table)
print(translated_text) # Output: httpstutorialreferencecom
output
httpstutorialreferencecom
string
package offers has a predefined string containing all punctuation symbols. You just need to import string
package to use it.
import string
print(string.punctuation)
output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~