17

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()
dreftymac
  • 31,404
  • 26
  • 119
  • 182
JTFouquier
  • 389
  • 1
  • 4
  • 17

2 Answers2

31

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 '.'.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 3
    I'm assuming it has been defined before, just like in the original code. – mkrieger1 Sep 20 '17 at 17:47
  • But `re.sub` hasn't been called before. `stuff` is just the original string at the beginning. – mkrieger1 Sep 20 '17 at 17:53
  • Ah, your right. I misread the OP's post. For some reason my brain replaced "stuff" with "string" ... and _now_ looking back at my answer, I still see it was pretty dumb. For the OP's use case, yours is clearly better. Sorry about that. – Christian Dean Sep 20 '17 at 17:56
3
tuple = (('__this__', 'something'),('__This__', 'when'),(' ', 'this'),('.', 'is'),('__', 'different'))

for element in tuple:
    stuff = re.sub(element[0], element[1], stuff)
Rômulo Tone
  • 115
  • 6