简体   繁体   中英

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?

>>> import re
>>> text = "Games & Fun"
>>> re.sub(r'\W+', '-', text)
'Games-Fun'
>>> re.sub(r'[&\s]+', '-', "Games & Fun")
'Games-Fun'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM