Python String translate() Method

Python string translate() function is used to replace specific characters in a string based on a translation table, which is created using the maketrans() method.

Syntax

string.translate(table)

Parameters

table(required): A dictionary or a mapping table that describes how to perform the replacement.

Return value

Returns a string where specified characters are replaced according to the provided translation table.

Visual RepresentationVisual Representation of Python String translate() Method

Example 1: How to Use translate() Method

dt = "Bilbo Baggins"

transTable = dt.maketrans("B", "K")

print(dt.translate(transTable))

Output

Kilbo Kaggins

Example 2: Translation/Mapping using a translation table

s1 = "Modric"
s2 = "Neymar"
s3 = "Mbappe"

string = "footballer"
print("Original string:", string)

translation = string.maketrans(s1, s2, s3)

# translate string
print("Translated string:", string.translate(translation))

Output

Original string: footballer

Translated string: feetllm

Example 3: Translation with a manual translation table

Here We manually create a translation table (in the form of a dictionary).

When using a dictionary, ASCII codes must be used instead of characters.
Visual Representation of Translation with translate() method with a manual translation table

trans_table = {82: None, 111: None, 104: 111}

str = "Rohit"
print("Original string:", str)

# translate string
print("Translated string:", str.translate(trans_table))

Output

Original string: Rohit

Translated string: oit

The R is removed, the o is removed, and the h is replaced by o. Thus, “Rohit” becomes “oit”.

Example 4: Remove Punctuation from a String in Python

import string

s1 = "Cristiano Ronaldo is a Portuguese professional footballer."

trans_table = str.maketrans("", "", string.punctuation)

translated_string = s1.translate(trans_table)

print(translated_string)

Output

Cristiano Ronaldo is a Portuguese professional footballer

You can see that the punctuation at the end of the original string (the period) is removed.

Example 5: Remove Vowels from a String

s1 = "Cristiano Ronaldo"
vowels = "aeiouAEIOU"

trans_table = str.maketrans('', '', vowels)
text_without_vowels = s1.translate(trans_table)

print(text_without_vowels)

Output

Crstn Rnld

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.