Python String maketrans() Method

Python String maketrans() method is used to create a translation table for use with the translate() method to replace specified characters.

Syntax

str.maketrans(x[, y[, z]])

Parameters

  1. x(required): If only one argument is passed, it must be a dictionary, mapping Unicode ordinals (integers) or characters (strings of length 1) to translation strings (of any length).
  2. y(optional): If two arguments are given, they must be strings of equal length. In this case, each character in x will be mapped to the character at the same position in y.
  3. z(optional):  If three arguments are passed, each character in the third argument is mapped to None.

Return value

It returns a transition table used by the translate() function.

Visual RepresentationVisual Representation of Python String maketrans() MethodExample 1: How to Use String maketrans() Method

h1 = "Ankit"
h2 = "Dhoni"

print(str.maketrans(h1, h2))

Output

{65: 68, 110: 104, 107: 111, 105: 110, 116: 105}

Example 2: Using maketrans() with translate() methodPython String maketrans() Method (with translate() method)

h1 = "Ankit"
h2 = "Dhoni"

h4 = str.maketrans(h1, h2)

print(h1.translate(h4))

Output

Dhoni

Example 3: Translation table using three strings 

h1 = "qwerty"
h2 = "bowled"
h3 = "qweled"
h4 = "qwerty"

print(h4.maketrans(h1, h2, h3))

Output

{113: None, 119: None, 101: None, 114: 108, 
 116: 101, 121: 100, 108: None, 100: None} 

Example 4: Value error

first_string = "ankit"
second_string = "krunal"

string = "ankit"

print(string.maketrans(first_string, second_string))

Output

ValueError: the first two maketrans arguments must have equal length

Leave a Comment

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