Home > Net >  How do I replace all of the specific characters in the string from the lists with the replacement ch
How do I replace all of the specific characters in the string from the lists with the replacement ch

Time:02-22

I'm trying to replace the "i", "s", and "p" in the string "Mississippi" with the second character of each list in the list below. When replacement is printed by itself, it will replace all of the characters with the character specified, but it will only actually replace the first character that I want to replace in the new string, not all of them. (Ex. Mlsslsslppl instead of Ml$$l$$lzzl) I don't really know where to go from here to fix this problem.

def substitutePairs(myString, pairsList):
    for item in myString:
        for separateList in pairsList:
            for char in separateList:
                if item == char:
                    replacement = separateList[1]
                    newString = myString.replace(item, replacement)

    return newString

def main():
    myString = "Mississippi"
    pairsList = [['i', 'l'],['s', '$'],['p', 'z']]
    print(substitutePairs(myString, pairsList))

if __name__ == "__main__":
    main()

CodePudding user response:

You need to iteratively apply replace to the previous result so that you can accumulate all of the substitutions into one string. A single loop over pairs_list is all you need; replace will do the work for you of iterating through my_string.

>>> def subst_pairs(my_string, pairs_list):
...     for x, y in pairs_list:
...         my_string = my_string.replace(x, y)
...     return my_string
...
>>> subst_pairs("Mississippi", [['i', 'l'],['s', '$'],['p', 'z']])
'Ml$$l$$lzzl'

CodePudding user response:

That really looks like a job for str.translate instead:

>>> 'Mississippi'.translate(str.maketrans('isp', 'l$z'))
'Ml$$l$$lzzl'

If you really have such a list (and can't use the above), you can still build the translation table from it:

def subst_pairs(my_string, pairs_list):
    return my_string.translate({ord(k): v for k, v in pairs_list})

Or:

def subst_pairs(my_string, pairs_list):
    return my_string.translate(str.maketrans(*map(''.join, zip(*pairs_list))))
  • Related