Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom table for str.translate in Python 3

If I run this code:

s.translate(str.maketrans({'as': 'dfg', '1234': 'qw'}))

I will get:

ValueError: string keys in translate table must be of length 1

Is there a way to replace multiple characters at once using str.translate? Docs says I can use codecs for flexible approach, but I can't find out how.

If no, what can be done instead then?

like image 526
Necronomicron Avatar asked Mar 05 '23 09:03

Necronomicron


1 Answers

No. str.translate can be used solely to replace single characters. The replacement strings can be of any length, but the keys must be a single character.


When they documentation mentions codecs they are saying that you can implement a custom encoding, register it and then open the file using it... it's not a matter of calling something like codecs.maketrans, it's quite some work. I'd personally use re.sub with a function replacement:

replacements = {'as': 'dfg', '1234': 'qw'}
re.sub('({})'.format('|'.join(map(re.escape, replacements.keys()))), lambda m: replacements[m.group()], text)

Which seems to do what you want:

>>> re.sub('({})'.format('|'.join(map(re.escape, replacements.keys()))), lambda m: replacements[m.group()], "test as other test1234")
'test dfg other testqw'
like image 119
Giacomo Alzetta Avatar answered Mar 19 '23 05:03

Giacomo Alzetta