Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace multiple occurrences of any special character by one in python

I have a string like:

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

And I want output like:

new_string = "happy.!"

I know how to replace multiple occurrence of any special character. It 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 each special character. But want to know if there is an easy way to write it for all special characters in one line.

like image 346
Shweta Avatar asked Jun 19 '15 10:06

Shweta


2 Answers

You can use \W to match any non-word character:

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

If you want to replace with same special character then use:

line = re.sub(r'(\W)(?=\1)', '', line)
like image 79
anubhava Avatar answered Sep 21 '22 04:09

anubhava


I think you mean this,

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

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

like image 24
Avinash Raj Avatar answered Sep 24 '22 04:09

Avinash Raj