简体   繁体   中英

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?

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'

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: as 1234
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM