×

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 Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.

Spell Corrector GUI using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

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.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

Sentiment Analysis using NLTK

Introduction Data is being produced at an astounding rate and volume in the field of the internet and other digital services nowadays. Researchers, engineers, and data analysts often work with tabular...

7 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python Num2words

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.