What is the purpose of string.maketrans?

5

I was taking a look at some Python challenges and found one that involved rotating the characters of a string. Type 'a' turns 'c', 'b' turns 'd', and at the end 'y' turns 'a' and 'z' turns 'b'.

As I solved 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.

    
asked by anonymous 27.02.2015 / 14:47

1 answer

5

The maketrans is used to map the characters so that they match. First you pass a string with the characters that will be "translated", then the mapping of it, where position one 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 this print will be:

ABCg

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

    
27.02.2015 / 15:04