I'm wondering if there's any way to combine patterns with re.sub()
instead of using multiples like below:
import re
s1 = "Please check with the store to confirm holiday hours."
s2 = ''' Hours:
Monday: 9:30am - 6:00pm
Tuesday: 9:30am - 6:00pm
Wednesday: 9:30am - 6:00pm
Thursday: 9:30am - 6:00pm
Friday: 9:30am - 9:00pm
Saturday: 9:30am - 6:00pm
Sunday: 11:00am - 6:00pm
Please check with the store to confirm holiday hours.'''
strip1 = re.sub(s1, '', s2)
strip2 = re.sub('\t', '', strip1)
print(strip2)
Desired output:
Hours:
Monday: 9:30am - 6:00pm
Tuesday: 9:30am - 6:00pm
Wednesday: 9:30am - 6:00pm
Thursday: 9:30am - 6:00pm
Friday: 9:30am - 9:00pm
Saturday: 9:30am - 6:00pm
Sunday: 11:00am - 6:00pm
If you're just trying to delete specific substrings, you can combine the patterns with alternation for a single pass removal:
pat1 = r"Please check with the store to confirm holiday hours."
pat2 = r'\t'
combined_pat = r'|'.join((pat1, pat2))
stripped = re.sub(combined_pat, '', s2)
It's more complicated if the "patterns" use actual regex special characters (because then you need to worry about wrapping them to ensure the alternation breaks at the right places), but for simple fixed patterns, it's simple.
If you had real regexes, rather than fixed patterns, you might do something like:
all_pats = [...]
combined_pat = r'|'.join(map(r'(?:{})'.format, all_pats))
so any regex specials remain grouped without possibly "bleeding" across an alternation.
You're not even using regular expressions so you may as well just chain replace
:
s1 = "Please check with the store to confirm holiday hours."
s2 = ''' Hours:
Monday: 9:30am - 6:00pm
Tuesday: 9:30am - 6:00pm
Wednesday: 9:30am - 6:00pm
Thursday: 9:30am - 6:00pm
Friday: 9:30am - 9:00pm
Saturday: 9:30am - 6:00pm
Sunday: 11:00am - 6:00pm
Please check with the store to confirm holiday hours.'''
strip2 = s2.replace(s1, "").replace("Hours:","").strip()
print(strip2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With