How to chain multiple re.sub() commands in Python [duplicate]
Asked Answered
B

2

18

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()
Bowl answered 20/9, 2017 at 17:40 Comment(5)
@Rawing, cool thanks that's better. My search wasn't showing that since I had re.sub(). Will delete.Bowl
Wait, actually should I keep this q since it's worded differently or delete it because it's a duplicate?Bowl
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.Orthochromatic
@Bowl See also #5669447Slow
Yes, I will just use str.replace() instead. SO won't let me close this. ha.Bowl
S
32

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

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

for element in tuple:
    stuff = re.sub(element[0], element[1], stuff)
Bushire answered 20/9, 2017 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.