Replace multiple characters using re.sub

Viewed 3927
s = "Bob hit a ball!, the hit BALL flew far after it was hit."

I need to get rid of the following characters from s

!?',;.

How to achieve this with re.sub?

re.sub(r"!|\?|'|,|;|."," ",s) #doesn't work. And replaces all characters with space

Can someone tell me what's wrong with this?

2 Answers

The problem is that . matches all characters, not the literal '.'. You want to escape that also, \..

But a better way would be to not use the OR operator |, but simply use a character group instead:

re.sub(r"[!?',;.]", ' ', s)

no need for regex, u can do it with simple str.replace(), something like this:

chars_to_replace = "!?',;."

def replace(text):
    for char in chars_to_replace:
        if char in text:
            text = text.replace(char, "")

    return text


my_text = "Bob hit a ball!, the hit BALL flew far after it was hit."


print replace(my_text)

// Bob hit a ball the hit BALL flew far after it was hit
Related