开发者

How to replace the quote " and hyphen character in a string with nothing in Python?

开发者 https://www.devze.com 2022-12-08 00:12 出处:网络
开发者_如何转开发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. Tha

开发者_如何转开发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.


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.


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


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.


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


In Python 2.6:

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

Returns:

Hey  How are you?
0

精彩评论

暂无评论...
验证码 换一张
取 消