×

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

Calculator Program in Python

Simple Calculator Program in Python This example helps to learn how to create a simple calculator program to perform operations like addition, subtraction, multiplication, and division. Source Code The following is the source...

2 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 Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Python Indentation

Overview The spaces at the start of a code line are known as an indentation in Python programming. Indentation is only used for readability in other programming languages like C, C++,...

8 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Python Unit Test Cheat String

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.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Captcha Code in Python with Example

Python Programming Language 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...

6 minutes read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

Python System Requirements

Introduction As we know, Python is a popular programming language usually used to write scripts for operating systems. It’s handy adequate for utilizing in web development and application design. In this article,...

2 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.