Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replace all special characters and spaces with single '-'

I am trying to replace all the special characters and spaces in the string with only single '-'

For example:

Input: "Games & Fun"

Output: "Games-Fun"

I tried

>>> re.sub('[&" "]', '-', "Games & Fun")
'Games---Fun'

But I want "Games-Fun" only.

Can anyone help me with this?


2 Answers

>>> import re
>>> text = "Games & Fun"
>>> re.sub(r'\W+', '-', text)
'Games-Fun'
like image 198
jamylak Avatar answered Dec 06 '25 16:12

jamylak


>>> re.sub(r'[&\s]+', '-', "Games & Fun")
'Games-Fun'
like image 43
Eastsun Avatar answered Dec 06 '25 16:12

Eastsun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!