Skip to main content

translate()

The translate() method in Python is a built-in string method that returns a string where each character is mapped to its corresponding character as per the translation table. This method is often used to replace specific characters with other characters in a string based on a mapping specified by the translation table.

Parameter Values

Parameter Description
table

A dictionary where each character in the string is mapped to its corresponding character in the table.

Return Values

The translate() method returns a new str with characters replaced or removed.

How to Use translate() in Python

Example 1:

The translate() method returns a string where each character is mapped to its corresponding character in the translation table.

translation_table = str.maketrans('aeiou', '12345')
print('apple'.translate(translation_table)) # Output: '1ppl2'
Example 2:

The translate() method can also delete characters by providing an empty mapping for those characters.

translation_table = str.maketrans('', '', 'aeiou')
print('apple'.translate(translation_table)) # Output: 'ppl'
Example 3:

The translate() method can be used with Unicode characters for more complex translations.

translation_table = {97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
print('apple'.translate(translation_table)) # Output: '1ppl2'