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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With