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.
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)
I think you mean this,
line = re.sub(r'(\W)\1+', r'\1', line)
https://regex101.com/r/eM5kV8/1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With