What is string.maketrans for?

Asked

Viewed 729 times

5

I was looking at some Python challenges and found one that involved rotating the characters of a string. Of type 'a' turns 'c', 'b' turns’d', and at the end 'y' turns 'a' and 'z' turns 'b'.

While solving the problem, I saw an indication that the best thing to do was to use string.maketrans, but I have no idea what the function does, or how to use it.

1 answer

5


The maketrans is used to map characters so that they match. First you pass a string with the characters that will be "translated", then the mapping of it, where the position of the map, corresponds to the translation of the first element of the passed string. This can be seen in the following example:

from string import maketrans

char_a_ser_convertida = 'abcdef'
mapa_de_traducao = 'ABCDEF'
traducao = maketrans(char_a_ser_convertida, mapa_de_traducao)
str = 'abcg'
print str.translate(traducao)

The output of that print will be:

ABCg

Note that he only converted the mapped characters to their corresponding characters on the map. Basically what it does is translate a character to a matching element in the mapping string.

  • 1

    It makes sense then. If I create a map with the whole alphabet, can solve the problem in a very simple way... Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.