20

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()
5
  • @Rawing, cool thanks that's better. My search wasn't showing that since I had re.sub(). Will delete. Commented Sep 20, 2017 at 17:50
  • Wait, actually should I keep this q since it's worded differently or delete it because it's a duplicate? Commented Sep 20, 2017 at 17:51
  • 1
    Honestly, I don't think it's worth keeping. But if you don't want to delete it, you can also close it as a duplicate. Commented Sep 20, 2017 at 17:54
  • 1
    @JTFouquier See also stackoverflow.com/questions/5668947/… Commented Sep 20, 2017 at 17:56
  • Yes, I will just use str.replace() instead. SO won't let me close this. ha. Commented Sep 20, 2017 at 17:59

2 Answers 2

35

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

Sign up to request clarification or add additional context in comments.

3 Comments

I'm assuming it has been defined before, just like in the original code.
But re.sub hasn't been called before. stuff is just the original string at the beginning.
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.
3
tuple = (('__this__', 'something'),('__This__', 'when'),(' ', 'this'),('.', 'is'),('__', 'different'))

for element in tuple:
    stuff = re.sub(element[0], element[1], stuff)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.