tags:

views:

192

answers:

5

I'd like to replace " and -

with "" nothing! make it disappear.

s = re.sub(r'[^\w\s]', '', s) this makes all punctuation disappear, but I just want those 2 characters. Thanks.

+2  A: 
re.sub('["-]+', '', s)
SilentGhost
+6  A: 

I'm curious as to why you are using a regular expression for this simple string replacement. The only advantage that I can see is that you can do it in one line of code instead of two, but I personally think that a replacement method is clearer than a regex for something like this.

The string object has a replace method - str.replace(old, new[, count]), so use replace("-", "") and replace("\"", "").

Note that my syntax might be a little off - I'm still a python beginner.

Thomas Owens
Probably because it was the accepted answer to his previous question: http://stackoverflow.com/questions/1545655/how-do-i-replace-all-punctuation-in-my-string-with-in-python/1545678#1545678
Fred Larson
or may be because he needs to replace multiple characters
SilentGhost
@Thomas: that'd be very slow
SilentGhost
SilentGhost, like I said, it's only two characters. To me, a regex would be more confusing when used in that situation.
Thomas Owens
And yes, it would be slower for large strings. And probably not Pythonic. If I had to remove more than 2 or 3 characters, I would use a regex.
Thomas Owens
+1  A: 

re.sub('[-"]', '', s)

Mez
A: 

In Python 2.6:

print 'Hey -- How are "you"?'.translate(None, '-"')

Returns:

Hey  How are you?
Nick Presta
Should be two spaces between Hey and How... cheater!
Triptych
There are...at least on my monitor.
Nick Presta
+2  A: 

In Python 2.6/2.7, you can use the helpful translate() method on strings. When using None as the first argument, this method has the special behavior of deleting all occurences of any character in the second argument.

>>> s = 'No- dashes or "quotes"'
>>> s.translate(None, '"-')
'No dashes or quotes'

Per SilentGhost's comment, this gets to be cumbersome pretty quickly in both <2.6 and >=3.0, because you have to explicitly create a translation table. That effort would only be worth it if you are performing this sort of operation a great deal.

Triptych
+1 for thinking alike!
Nick Presta
I knew I shouldn't have typed all that explanatory text.
Triptych
works only in py2.6, in py3k it's more cumbersome than that
SilentGhost