Replace multiple occurrences of any special character with one in python

I have a line like:

string = "happy.....!!!"

      

And I want the output to look like this:

new_string = "happy.!"

      

I know how to replace the multiple occurrence of some special character. This can be done as follows:

line = re.sub('\.+', '.', line)

      

But I want to replace it for all special characters like ",. / \, Etc. One way is to write it for every special character. But I want to know if there is an easy way to write it for all special characters on one line ...

+3


source to share


2 answers


You can use \W

to match any character other than a word:

line = re.sub(r'\W+', '.', line)

      




If you want to replace the same special character, use:

line = re.sub(r'(\W)(?=\1)', '', line)

      

+6


source


I think you mean this,

line = re.sub(r'(\W)\1+', r'\1', line)

      



https://regex101.com/r/eM5kV8/1

+4


source







All Articles