L
L
Lorem Ipsum2014-07-12 01:00:01
Python
Lorem Ipsum, 2014-07-12 01:00:01

How to use ord, chr, translate+maketrans in python?

Hey!
I want to translate using standard python functions
1. translate https://docs.python.org/3.4/library/stdtypes.html?...
2. maketrans https://docs.python.org/3.4/ library/stdtypes.html?... 3. ord ,
chr https://docs.python.org/3.4/howto/unicode.html
Is it somehow overcome?
For example, I can do this

>>> tbl = maketrans('евица', 'evica')
>>> print('чечевица'.translate(tbl))
чeчeviцa

But I can't do it like this
>>> print('чечевица'.translate(tbl.update({
           ord('ч'): ord('ch'), # I cant do it, because ord accept only one letter, no more
       })))
# I want get this result: chechevica

How can I do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yttrium, 2014-07-12
@yttrium

from what angle not to enter:
one Unicode character cannot be replaced by two characters
; two bytes are not translated into two bytes, because transmitted one by one. Of course, you can translate the components of the character, but this is not convenient
As the zen of python says - make it simple

import re
res = re.compile(r'\w')
tbl = {'ч':'ch'..}
print(res.sub(lambda x: tbl[x.group()], 'чечевица')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question