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()
made this to find all with multiple #regular #expressions. regex1 = r"your regex here" regex2 = r"your regex here" regex3 = r"your regex here" regexList = [regex1, regex1, regex3] for x in regexList: if re. findall(x, your string): some_list = re. findall(x, your string) for y in some_list: found_regex_list.
As long as you can make do with str. replace() , you should use it. It avoids all the pitfalls of regular expressions (like escaping), and is generally faster.
A character in Python is also a string. So, we can use the replace() method to replace multiple characters in a string. It replaced all the occurrences of, Character 's' with 'X'.
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 '.'
.
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