Skip to content Skip to sidebar Skip to footer

Replace Multiple Characters In A String Using A Set Of Rules

Rules in applyRules is going to be asked to users, but it does not work what it should work which is [“character1:substitution”, “character2:substitution”] When user put ['

Solution 1:

If you have multiple rules, this becomes cumbersome. As long as your replacements are done on single characters, you can make this easy with str.translate. That, however, doesn't solve the problem of chained replacements, so you'll have to make use of a while loop that runs until there are no more changes.

def applyRules(string, rules):
    mapping = str.maketrans(dict(x.split(':') for x in rules))

    while True:
        new = string.translate(mapping)
        ifstring == new:
            breakstring = newreturnnew

In [1308]: applyRules('bbbbb', ['b:c', 'c:d'])
Out[1308]: 'ddddd'

Single Character Replacement For replacement involving a single character, the solution simplifies. You could use a dictionary with get:

def applyRules(char, rules):
    mapping =dict(x.split(':') for x in rules)

    while True:
        new = mapping.get(char, char)
        ifchar == new:
            breakchar = newreturnnew

This should be much simpler.

Solution 2:

You need to apply each and every rule and also, preserve the new string at the same time since strings are immutable in python. You can use translate of str class. Following code works

def applyRules(char, rules):
    modified = charfor rule in rules:
        r = rule.split(':')
        table = str.maketrans({r[0]:r[1]})
        modified = modified.translate(table)

    return modified

print(applyRules('bbbbb',['b:c','c:d'])) #prints 'ddddd'print(applyRules('abdecbc',['b:c','c:d'])) #prints 'addeddd'

Post a Comment for "Replace Multiple Characters In A String Using A Set Of Rules"