pythonregexfluent-interface

How to chain multiple re.sub() commands in Python


I would like to do multiple re.sub() replacements on a string and I'm replacing with different strings each time.

This looks so repetitive when I have many substrings to replace. Can someone please suggest a nicer way to do this?

stuff = re.sub('__this__', 'something', stuff)
stuff = re.sub('__This__', 'when', stuff)
stuff = re.sub(' ', 'this', stuff)
stuff = re.sub('.', 'is', stuff)
stuff = re.sub('__', 'different', stuff).capitalize()

Solution

  • Store the search/replace strings in a list and loop over it:

    replacements = [
        ('__this__', 'something'),
        ('__This__', 'when'),
        (' ', 'this'),
        ('.', 'is'),
        ('__', 'different')
    ]
    
    for old, new in replacements:
        stuff = re.sub(old, new, stuff)
    
    stuff = stuff.capitalize()
    

    Note that when you want to replace a literal . character you have to use '\.' instead of '.'.