Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i need to know exactly how to use string.maketrans [closed]

Tags:

I am new to python, please can any one tell me how to use string.maketrans (), with some examples please ?

I find some like:

allchars = string.maketrans ('', '')

that return the character map, but i couldn't figure out how to use this approach

Thanks for your help

like image 516
Oussama Elgoumri Avatar asked Apr 04 '13 15:04

Oussama Elgoumri


People also ask

How does STR Maketrans () work?

The string maketrans() method returns a mapping table for translation usable for translate() method. In simple terms, maketrans() method is a static method that creates a one to one mapping of a character to its translation/replacement. It creates a Unicode representation of each character for translation.

How do I use Maketrans in Python 3?

Python 3 - String maketrans() MethodThe maketrans() method returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. Then this table is passed to the translate() function. Note − Both intab and outtab must have the same length.


1 Answers

After you've created a translation table using string.maketrans, you can use the result of that to the str.translate method, eg:

import string
trans = string.maketrans('ae', 'bx') # a->b and e->x
text = 'abcdef'
print text.translate(trans)
# bbcdxf
like image 76
Jon Clements Avatar answered Nov 19 '22 04:11

Jon Clements