使用python中的字符串输入数组重写多个附加替换方法的更好方法?
我有一个非常丑陋的命令,我使用许多附加的replace()"方法来替换/替换/清除原始字符串中的许多不同字符串.例如:
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 = 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,', '')
如您所见,这是一个非常丑陋的语句,并且很难知道长命令中的字符串是什么.这也使得难以重复使用.
As you can see, it's a very ugly statement and makes it very difficult to know what strings are in the long command. It also makes it hard to reuse.
我想做的是定义一个包含许多替换对的输入数组,其中替换对看起来像 [
;其中更大的数组看起来像:
What I'd like to do is define an input array of of many replacement pairs, where a replacement pair looks like [<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>]
; where the greater array looks something like:
replacementArray = [
[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
[<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>]
]
AND,我想传递该replacementArray,以及需要清理的原始字符串到具有如下结构的函数:
AND, I'd like to pass that replacementArray, along with the original string that needs to be scrubbed to a function that has a structure something like:
def replaceAllSubStrings(originalString, replacementArray):
newString = ''
for each pair in replacementArray:
perform the substitution
return newString
我的问题是:编写函数代码块以应用replacementArray中的每一对的正确方法是什么?我应该使用replace()"方法吗?sub()"方法?我对如何将原始代码重组为一个漂亮的干净函数感到困惑.
MY QUESTION IS: What is the right way to write the function's code block to apply each pair in the replacementArray? Should I be using the "replace()" method? The "sub()" method? I'm confused as to how to restructure the original code into a nice clean function.
预先感谢您提供的任何帮助.
Thanks, in advance, for any help you can offer.
您的想法是正确的.使用序列解包来迭代每对值:
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