Jiloc
Jiloc

Reputation: 3658

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)

Upvotes: 1

Views: 5249

Answers (1)

dcsordas
dcsordas

Reputation: 232

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.

Upvotes: 3

Related Questions