×

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 Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Python Functionalities of Pillow Module

This instructional exercise is about "Pillow" library, one of the significant libraries of python for picture control. Pillow library of python, is an easy to use and also open source...

14 minutes read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Notepad++ For Python

In this article, you are going to learn what notepad++ is and how it is integrated with python to use the python programming language. You can also learn how to...

4 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Comment starts with the symbol in Python

Python programming language: 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...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.