I am looking to replace character pairs in a string using a dictionary in python.
It works for single characters but not doubles.
txt = "1122"
def processString6(txt):
dictionary = {'11': 'a', '22':'b'}
transTable = txt.maketrans(dictionary)
txt = txt.translate(transTable)
print(txt)
processString6(txt)
Error Message:
ValueError: string keys in translate table must be of length 1
Desired output:
ab
I'v also tried
s = ' 11 22 '
d = {' 11 ':'a', ' 22 ':'b'}
print( ''.join(d[c] if c in d else c for c in s))
but likewise it doesn't work
looking to use a dictionary as opposed to .replace()
as I just want to scan the string once as.replace() does a scan for each key,value
You can use this piece of code to replace any length of strings:
import re
txt = "1122"
def processString6(txt):
dictionary = {'11': 'a', '22':'b'}
pattern = re.compile(
'|'.join(sorted(dictionary.keys(), key=len, reverse=True)))
result = pattern.sub(lambda x: dictionary[x.group()], txt)
return result
print(processString6(txt))
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.