简体   繁体   中英

Python String replacing special characters

I need to replace "-" with spaces (but not more than 1 consecutively, and strip everything at the beginning and at the end) and delete any other special character, some examples:

    "Example-1" ---> "Example 1"  
    "Example - 2"---> "Example 2"  
    "Ex amp le-(3)"--->"Ex amp le 3"  
    "--Example%s,,4 "--->"Examples4"  

Resolved

(I have to edit the question because I have just 8 reputation and I can't answer my own question for 5 more hours)

I resolved this question like this:

 my_string = re.sub('[^\w -]', '', my_string).replace('-', ' ').strip(' ')
 subsMade = 1
 while subsMade > 0:
     (my_string, subsMade) = re.subn('  ', ' ', my_string)

I agree with zigg, you'll need reg ex for that. You can find a gentle introduction here: http://www.diveintopython.net/regular_expressions/index.html#re.intro (check 'Street Address' case study, it shares some similarities with what you want to do).

EDIT:

I'm not a reg ex guru, but...

import re

pattern = "[- ]+"
re.sub(pattern, " ", your_string)

This will parse your first two examples. I'm not sure if all you need can be done in a single pattern... May some wise men come along.

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