Python String translate() Method
Python String translate() returns a string that is a modified string of givens string according to given translation mappings.
There are two ways to translate.
- Python String translate() with mapping as a dictionary
- Mapping using maketrans()
Method 1. Providing a mapping as a dictionary
Syntax: string.translate(mapping)
Parameter: mapping: A dictionary having mapping between two characters.
Returns: Returns modified string where each character is mapped to its corresponding character according to the provided mapping table.
Example 1:
In this example, we are going to see how to use Python string translate() methods with a dictionary.
Python3
# Python3 code to demonstrate# translations without# maketrans()# specifying the mapping# using ASCIItable = { 119 : 103, 121 : 102, 117 : None }# target stringtrg = "weeksyourweeks"# Printing original stringprint ("The string before translating is : ", end ="")print (trg)# using translate() to make translations.print ("The string after translating is : ", end ="")print (trg.translate(table)) |
Output:
The string before translating is : weeksyourweeks The string after translating is : geeksforgeeks
Example 2:
Python3
# Python 3 Program to show working# of translate() method# specifying the mapping # using ASCII translation = {103: None, 101: None, 101: None}string = "geeks"print("Original string:", string)# translate stringprint("Translated string:", string.translate(translation)) |
Output:
Original string: geeks Translated string: ks
Method 2. Providing a mapping using maketrans()
In this method, we will use mapping with maketrans() methods.
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()
Python3
# Python 3 Program to show working# of translate() method# First StringfirstString = "gef"# Second StringsecondString = "eks"# Third StringthirdString = "ge"# Original Stringstring = "geeks"print("Original string:", string)translation = string.maketrans(firstString, secondString, thirdString)# Translated Stringprint("Translated string:", string.translate(translation)) |
Output:
Original string: geeks Translated string: ks



Please Login to comment...