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?
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'