A better way to rewrite multiple appended replace methods using an input array of strings in python?

前端 未结 2 1747
心在旅途
心在旅途 2021-01-16 17:09

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:

<
相关标签:
2条回答
  • 2021-01-16 17:55

    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.

    0 讨论(0)
  • 2021-01-16 18:10

    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
    
    0 讨论(0)
提交回复
热议问题