Python String translate() Examples
There are two ways to translate are:
- Python String translate() with mapping as a dictionary.
- Mapping using maketrans().
Translation/Mapping with translate() with manual translation table
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 ASCII table = { 119 : 103 , 121 : 102 , 117 : None } # target string trg = "weeksyourweeks" # Printing original string print ( "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 : w3wiki
Translation/Mapping using a translation table with translate()
In the given example, the vowels are replaced with digits with the use of maketrans() and translate() in Python.
Python3
# Define the translation table table = str .maketrans( 'aeiou' , '12345' ) # Apply the translation to a string text = 'this is a test' translated_text = text.translate(table) print (translated_text) # 'th3s 3s 1 t2st' |
Output :
th3s 3s 1 t2st
Python String translate() Method
Python String translate() returns a string that is a modified string of givens string according to given translation mappings.