A Better Way To Rewrite Multiple Appended Replace Methods Using An Input Array Of Strings In Python?
I have a really ugly command where I use many appended 'replace()' methods to replace/substitute/scrub many different strings from an original string. For example: newString = ori
Solution 1:
You have the right idea. Use sequence unpacking to iterate each pair of values:
def replaceAllSubStrings(originalString, replacementArray):
for in_rep, out_rep in replacementArray:
originalString = originalString.replace(in_rep, out_rep)
return originalString
Solution 2:
How about using re
?
import re
def make_xlat(*args, **kwds):
adict = dict(*args, **kwds)
rx = re.compile('|'.join(map(re.escape, adict)))
def one_xlat(match):
return adict[match.group(0)]
def xlat(text):
return rx.sub(one_xlat, text)
return xlat
replaces = {
"a": "b",
"well": "hello"
}
replacer = make_xlat(replaces)
replacer("a well?")
# b hello?
You can add as many items in replaces
as you want.
Post a Comment for "A Better Way To Rewrite Multiple Appended Replace Methods Using An Input Array Of Strings In Python?"