问题描述
我有一个非常丑陋的命令,其中我使用了许多附加的“ replace()”方法来替换/替换/清除原始字符串中的许多不同字符串。 例如:
newString = originalString.replace(' ', '').replace("\n", '').replace('()', '').replace('(Deployed)', '').replace('(BeingAssembled)', '').replace('ilo_', '').replace('ip_', '').replace('_ilop', '').replace('_ip', '').replace('backupnetwork', '').replace('_ilo', '').replace('prod-', '').replace('ilo-','').replace('(EndofLife)', '').replace('lctcvp0033-dup,', '').replace('newx-', '').replace('-ilo', '').replace('-prod', '').replace('na,', '')
如您所见,这是一个非常丑陋的语句,很难知道long命令中的字符串。 这也使得很难重用。
我想做的是定义一个包含许多替换对的输入数组,其中替换对看起来像[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>]
;
更大的数组看起来像这样:
replacementArray = [
[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>]
]
AND ,我想将那个replaceArray以及需要清理的原始字符串传递给具有以下结构的函数:
def replaceAllSubStrings(originalString, replacementArray):
newString = ''
for each pair in replacementArray:
perform the substitution
return newString
我的问题是:编写函数的代码块以在replaceArray中应用每一对的正确方法是什么? 我应该使用“ replace()”方法吗? “ sub()”方法? 我对于如何将原始代码重组为一个不错的干净函数感到困惑。
预先感谢您提供的任何帮助。
1楼
你有正确的主意。 使用序列拆包来迭代每对值:
def replaceAllSubStrings(originalString, replacementArray):
for in_rep, out_rep in replacementArray:
originalString = originalString.replace(in_rep, out_rep)
return originalString
2楼
使用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?
您可以根据需要在replaces
添加任意数量的项目。