codingstreets
Search
Close this search box.
python-maketrans-method

Introduction To Python Maketrans Method With practical Examples

In This Article You Will Learn About Python maketrans Method

Python maketrans method – Before moving ahead, let’s know a little bit about Python translate() method

Introduction – It creates or returns a mapping table that can be used with translate() method to replace specified characters.

Syntax – String.maketrans(x, y, z)

Parameter Values -

x – It is required value. If one parameter is specified then it has to be dictionary to describe how to replace a specified character. If two or more parameter is specified then it has to be string that specifying the character to be replaced.

y – It is an optional value. Its parameter should be same as parameter x. Each character in parameter x will be replaced with this parameter.

z - It is an optional value. A string describes which character has to be removed from original string.        

Example 1 – Replaced a specified letter ‘H’ with ‘J’

txt = "Hello Python!"
mydict = txt.maketrans('H' , 'J')

print(txt.translate(mydict))
python-maketrans-method
As it is shown clearly that it replaced first letter ‘H’ to ‘J’ and returned new string

Example 2 – Use of mapping table with third parameter to remove original characters from string. 

w = "Hello Python World!"
x = 'Heoll' 
y = 'Jeoll' 
trans= w.maketrans(x , y)
  
print("Translated string:" , w.translate(trans))
python-maketrans-method
As it is shown clearly that it replaced string using third parameter and returned new string

Example 3 – Use of mapping table with third parameter to remove original characters from string. 

w = "Hello Python World!"
x = 'Hello' 
y = 'Jello' 
z = 'l' 
trans= w.maketrans(x , y , z) # translate string

print("Translated string:" , w.translate(trans))
python-maketrans-method
As it is shown clearly that it replaced string and returned new string

Example 4 – The method maketrans() itself returns a dictionary to describe each replacement, in unicode:

w = "Hello Python World!"
x = 'Hello' # 
y = 'Jello' 
z = 'l' 

print('Translated String:' , w.maketrans(x , y , z)) 
python-maketrans-method
As it is shown clearly that maketrans() itself returned a dictionary to describe each replacement, in unicode

If you find anything incorrect in above discussed topic and have any further question, please comment down below.

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on