mercredi 18 mars 2020

multipattern substitution along with whitespace in python

input :- "good && toast&&guest &fast& slow||wind ||old|| new || very good"
requirement :- replace " && " with "and" (similarly " || " with "or") so my output for above should be as below
Output :- "good and toast&&guest &fast& slow||wind ||old|| new or very good"

What I tried to do:-

import re

new_ = {
                                '&&':'and',
                                '||':'or'
}

inpStr = "good && toast&&guest &fast& slow||wind ||old|| new || very good"
replDictRe = re.compile( r'(\s%s\s)' % '\s|\s'.join(map(re.escape, new_.keys())))
oidDesStr = replDictRe.sub(lambda mo:new_.get(mo.group(),mo.group()), inpStr)
print(oidDesStr)

Aucun commentaire:

Enregistrer un commentaire