Skip to content
Home » String Mapping in Python

String Mapping in Python

Spread the love

In the previous article we were talking about replacing substrings by other substrings.

You may also want to read about other string methods that I covered in my previous articles. If so, here they are:

1) joining strings

2) splitting strings

3) stripping strings

In this article we’ll be talking about string mapping.

Here’s the video version of this article:

We can map some characters in the string to other characters. We’ll make use of two methods, which usually work together: maketrans(intab, outtab) and translate.

The former takes 2 arguments: intab and outtab, which are both strings of the same length, and returns a translation table, which is then used by the translate method.

But let’s take it easy:

The translation table maps each character in the intab string to the character in the outtab string which is at the same index. For example we can have the following translation table:

string mapping

The translation table tells the translate method that it should map each occurrence of the character ‘a’ to ‘y’, ‘e’ to ‘m’, etc.

Here’s how the two methods work together:

>>> intab = "aeiou"
>>> outtab = "ymx.$"
>>> text = "So, after all the changes are applied, you won't recognize this text."
>>> translation_tab = text.maketrans(intab, outtab)
>>> print(text.translate(translation_tab))
S., yftmr yll thm chyngms yrm ypplxmd, y.$ w.n't rmc.gnxzm thxs tmxt.

We can also use the maketrans method with a third parameter, which includes the characters to be deleted.

Let’s see how it works on the same example:

>>> text = "So, after all the changes are applied, you won't recognize this text."
>>> intab = "aeiou"
>>> outtab = "ymx.$"

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Before the translate method translates the characters, we want to delete all a’s and l’s from the string:

>>> deltab = "al"
>>> translation_tab = text.maketrans(intab, outtab, deltab)

In the output we can see that there are fewer characters than before due to the fact that some were deleted:

>>> print(text.translate(translation_tab))
S., ftmr  thm chngms rm ppxmd, y.$ w.n't rmc.gnxzm thxs tmxt.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply