Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

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()
like image 438
JTFouquier Avatar asked Sep 20 '17 17:09

JTFouquier


People also ask

How do you do multiple regex in Python?

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.

Is Re sub faster than string replace?

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.

How do you replace multiple characters in Python?

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


1 Answers

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

like image 99
mkrieger1 Avatar answered Oct 25 '22 15:10

mkrieger1