Skip to content Skip to sidebar Skip to footer

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 m

Solution 1:

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'

Solution 2:

The translate method of a string replaces one character by a string according to the translation that you provide.

Here are a few cases:

Original string: as1234
Error in [s.translate(str.maketrans({'as': 'dfg', '1234': 'qw'}))]
Error in [s = s.translate(str.maketrans({'a': 'd', '12': 'q'}))]
s.translate(str.maketrans({'a': 'd', '1': 'q'})): ds q234

Workaround to get the result

After the edit of the question, here is a solution to get the desired replacements:

Split by the keys, and then join by the values in your translation dictionary.

Replaced all subsrings: dfg qw

The code:

s = 'as 1234'print('Original string:',s)
try:
    w = s.translate(str.maketrans({'as': 'dfg', '1234': 'qw'}))
    print("s.translate(str.maketrans({'as': 'dfg', '1234': 'qw'}):", w)
except:
    print("Error in [s.translate(str.maketrans({'as': 'dfg', '1234': 'qw'}))]")
try:   
    w = s.translate(str.maketrans({'a': 'd', '12': 'q'}))
    print("s.translate(str.maketrans({'a': 'd', '12': 'q'})):", w)
except:
    print("Error in [s = s.translate(str.maketrans({'a': 'd', '12': 'q'}))]")
try:   
    w = s.translate(str.maketrans({'a': 'd', '1': 'q'}))
    print("s.translate(str.maketrans({'a': 'd', '1': 'q'})):", w)
except:
    print("Error in [s = s.translate(str.maketrans({'a': 'd', '1': 'q'}))]")

trans_dict = {'as': 'dfg', '1234': 'qw'}
for k,v in trans_dict.items():
    y = s.split(k)
    s = v.join(y)
print('Replaced all subsrings:',s)

Post a Comment for "Custom Table For Str.translate In Python 3"