Python String translate: The Complete Guide

0
26
Python String translate() Function with Example

Python translate() function returns a string in which each character has been mapped through the given translation table.

Python String translate()

The string translate() is a built-in Python function that returns a string where any specified characters are replaced with the character defined in a dictionary or a mapping table. The translate() function takes a table as a parameter and returns a string where each character is mapped to its corresponding character as per the translation table.

There are two ways that you can use to translate the string in Python.

  1. Using dictionary
  2. Use the maketrans() method to create a mapping table.

To create a mapping table in Python, use the maketrans() method. Then, the maketrans() function is used to construct the transition table.

If the character is not defined in the dictionary/table, the character will not be replaced.

Syntax

string.translate(table)

Parameters

The translate() function takes a table as a required parameter, either a dictionary or a mapping table describing how to perform the replace.

Return value

The translate() function returns a string where each character is mapped to its corresponding character as per the translation table.

Example

dt = "Bilbo Baggins"
transTable = dt.maketrans("B", "K")
print(dt.translate(transTable))

Output

Kilbo Kaggins

Here, the translation mapping translation contains the mapping from B to K.

Translation/Mapping using a translation table with translate()

# first string
first_string = "xy"
second_string = "zw"
third_string = "ab"

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

translation = str.maketrans(first_string, second_string, third_string)

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

Output

Original string: xyzwab
Translated string: zwzw

Translation with translate() with a manual translation table

# translation table - a dictionary
trans_table = {65: None, 66: None, 67: 105}

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

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

Output

Original string: ABCDEF
Translated string: iDEF

Here, we don’t create a translation table from maketrans() but manually create the mapping dictionary translation.

That is it for the string translate() method in Python.

Leave A Reply

Please enter your comment!
Please enter your name here

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