Python 3.x: using string.maketrans () to create a Unicode character conversion

I would like to write the following code:

import string frm = b'acdefhnoprstuw' to = 'אקדיפהנופרסתאו' trans_table = string.maketrans(frm, to) hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table) 

The above code does not work, because the to parameter for string.maketrans(frm, to) should be a byte sequence, not a string. The problem is that byte sequences can only contain ASCII alphabetic characters. Therefore, I cannot make a transformation that translates English strings to Hebrew strings. The reason is because string.maketrans() is extracting a byte object.

Is there an elegant way to use string.maketrans() and translate() functions (or equivalent functions that work with unicode) for my task?

+8
python string unicode
source share
1 answer

You need to use str.maketrans (), which takes two lines as arguments.

 >>> frm = 'acdefhnoprstuw' >>> to = 'אקדיפהנופרסתאו' >>> trans_table = str.maketrans(frm, to) >>> hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table) >>> hebrew_phrase 'פיאר קאתס דייפיר תהאנ סוורדס' 

String.maketrans still exists in Python 3.1, but that is simply because they missed moving it to bytes.maketrans () in 3.0. It was deprecated in 3.1 already and at 3.2 it left.

+13
source share

All Articles