Related Articles

Related Articles

Python | String translate()
  • Last Updated : 24 Jul, 2020

translate() returns a string that is modified string of givens string according to given translation mappings.

There are two ways to translate :

Providing a mapping as a dictionary

Parameters :

string.translate(mapping)

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.



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output:

The string before translating is : weeksyourweeks
The string after translating is : geeksforgeeks

One more example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 string
print("Translated string:"
       string.translate(translation))

chevron_right


Output:

Original string: geeks
Translated string: ks
Providing a mapping using maketrans()

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 needs to be deleted.

Returns : Returns the translation table which specifies the conversions that can be used by translate()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 Program to show working
# of translate() method
  
# First String
firstString = "gef"
  
# Second String
secondString = "eks"
  
# Third String
thirdString = "ge"
  
# Original String
string = "geeks"
print("Original string:", string)
  
translation = string.maketrans(firstString, 
                               secondString, 
                               thirdString)
  
# Translated String
print("Translated string:"
       string.translate(translation))

chevron_right


Output:

Original string: geeks
Translated string: ks

Output :

Original string: geeks
Translated string: ks

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :