Replace multiple characters using re.sub

Wkhan
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?

Tomerikoo

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Replace second and last second characters, using re.sub

re.sub replace substring between two specific characters multiple times

Replace strings in a list (using re.sub)

Replace "&&" with "and" using re.sub in python.

How to replace character $ by using re.sub?

Python re.sub(): trying to replace escaped characters only

Substituting multiple values in R using Sub or replace

re.sub to replace multiple lists with corresponding matches (Python)

How to replace characters based on variables in a list using regex sub

python - remove whitespace between two characters using re.sub

Replace a character with multiple characters using Python

Replace multiple characters in a string using a set of rules

Using python re.sub, but it replace the start and end unexpected

Using re.sub with capture groups to replace only portion of a match

Using re.sub() to replace some part of a string

How to replace a word suffix using re.sub() in Python?

How to search and replace exact character and number using re.sub?

Replace a digit in a sentence using re.sub() in python

Using re.sub() in python to replace html code

How to replace multiple characters instead of using replace n times

Replace multiple characters in C# using .replace without creating a loop

How to replace multiple instances of a sub strings in a string using a for loop (in a function)?

Replacing only the captured group using re.sub and multiple replacements

Mask multiple sensitive data using re.sub?

Using DOTALL breaks re.sub after replacing multiple times

Fix KeyError: '\\s' when trying to replace a substring with one that includes special characters with re.sub() or re.subn() method

Converting strings in a dataframe to uppercase using the python re package replace function (re.sub)

replace multiple characters with replaceAll

Replace multiple characters atomicaly