×

Python maketrans() function

Introduction

A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters that must be added to or subtracted from the entire string. This maketrans() method for transition generates a Unicode representation of each character. This post will go into great detail regarding the maketrans Python method and provide several examples.

The translation mapping is utilized in the translate() function to replace a character or its mapped character. Assuming we have a string called string, the following syntax can be used to apply the maketrans() method to it:

When using the function string.maketrans(a[,b[,c]]), b and c are optional parameters.

maketrans() Parameters for Strings

The string maketrans() function takes three parameters:

  • a: If the maketrans() function is given only one argument, it must be a dictionary by definition. This dictionary includes a one-to-one mapping of a single character of a string to its translations or a Unicode number, such as 97 for "a," to its translation.
  • b: If the maketrans() method receives two arguments, they must necessarily be equal-length strings with every character in the 1st string serving as a replacement for its corresponding index character in the second string.
  • c: In this instance, every character is mapped to None when three arguments are given.

The String maketrans function's return value ()

The translate() function can employ the conversions that are specified in the transition table that the string maketrans() function returns, which has a one-to-one mapping.

Example 1: Using a dictionary and maketrans() to create a translation table

The implementation of the maketrans() function with a single argument is shown in the sample code below:

Code:

# a sample dictionary with mapping from characters "x," "y," and "z"


dict_1 = {"x": "444", "y": "555", "z": "666"}


string = "xyz"


print (string.maketrans (dict_1))


# a model dictionary demonstrating mapping from Unicode numbers


dict_2 = {107: "222", 108: "333", 109: "444"}


string = "mno"


print(string.maketrans(dict_2))

Output:

{120: '444', 121: '555', 122: '666'}
{107: '222', 108: '333', 109: '444'}

Explanation

First, the definition of the dictionary with the name dictionary is given, which maps the letters x, y, and z to the numbers 444, 555, and 666, respectively. The maketrans() function replaces the characters in the string according to how they are represented in the dictionary. We can see from the output that 120("x") is mapped to "444," 121("y") is mapped to "555," and 122("z") is mapped to "666." In a similar manner, we can confirm the second result as well.

NOTE: If a character appears twice or more in the dictionary, an exception is raised.

Example 2: Making use of maketrans() and a translation table with two strings 

The implementation of the maketrans() function with 2 arguments is shown in the sample code below:

Code:

first__string ="mno"
second__string = "pqr"
string = "mno"
print (string.maketrans (first__string, second__string))
first__string = "mno"
second__string = "apoyo"
string = "mno"
print (string.maketrans (first__string, second__string))

Output:

{109: 112, 110: 113, 111: 114}
Traceback (most recent call last):
  File "d:\Programming\Python\tempCodeRunnerFile.py", line 9, in <module>
    print (string.maketrans (first__string, second__string))
ValueError: the first two maketrans arguments must have equal length

Explanation

In the code above, we see that a transition was established when the strings were equal in length; 109("m") is translated to 112("p"), 110("n") to 113("q"), and 111("o") to 114("r"). It provided a one-to-one mapping between each character's Unicode ordinal in the 1st string and the character's Unicode ordinal found at the same index in the 2nd string.

It raises ValueError as seen above when we attempt to establish a translating table for 2 strings that are not the same length.

Example 3: Translation table with detachable string and maketrans()

The maketrans() function with three arguments is implemented in the sample code below:

Code:

first_String = "mno"
second_String = "pqr"
third_String = "mnx"
string = "mno"
print (string.maketrans(first_String, second_String, third_String))

Output:

{109: None, 110: None, 111: 114, 120: None}

Explanation

In the aforementioned test example, we can see that after creating the mapping between the 1st and 2nd string's characters, it is later reset to None for the first and third string's characters. It is also possible to make mappings for nonexistent characters; for instance, 120('x') is mapped to None.

Frequently Asked Questions:

1. What do Python's Maketrans do?

The string maketrans() function is a static method, to be precise. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters that must be added to or subtracted from the entire string.

This maketrans() method for transition generates a Unicode representation of every character.

2. How does Python translate?

The maketrans() method for transition generates a Unicode representation for each character. The translate() function in Python uses these mappings to do the translation.

Here is a Python program that demonstrates how the translate() method works with mappings produced by the maketrans() method.

Code:

# 1st String
first__string = "wef"
# 2nd String
second__string = "eks"
# 3rd String
third__string = "we"
# The Original String being printed
str = "weeks"
print ("Rudimentary str is:", str)
translation__mapping = str.maketrans(first__string, second__string, third__string)
# Printing the Translated String
print ("Translated str is:", str.translate(translation__mapping))

Output:

Rudimentary str is: weeks
Translated str is: ks

3. How does a string get translated in Python?

The string translate() function is used to translate a string, and it produces a changed string in which every character has been mapped to its matching character according to the mapping table. The translate() method receives a dictionary storing all the mappings as an argument. When a character is not listed in the dictionary, it will not be changed.

The code for a translation without maketrans() is shown below as an example. It specifies the mapping utilizing ASCII values.

Code:

mapping = { 111 : 118, 120 : 101, 116 : None }
target__string = "javaTpoint"
print ("Before translating, the string is : ", end ="")
print (target__string)
print ("After translating, the string is : ", end ="")
print (target__string.translate (mapping))

Output:

Before translating, the string is :javaTpoint
After translating, the string is :javaTpvin

Related Topics

Python exe() function

Python exe() function The exec() function in Python executes the specified Python code and accepts large blocks of code. It supports dynamic execution of Python code where the object must be either a string...

1 minute read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

Python delattr() function

Python delattr() function The delattr() function in Python is used to delete the named attribute from the object, with the prior permission of the object. Syntax delattr(object, name) Parameter object : This parameter represents the object from which...

1 minute read.

Poolmanager in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

Python Key Error

What is an Error? Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called...

6 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

3 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.