Search code examples
pythonstringstrip

Strip Specific Punctuation in Python 2.x


I'm using Python v2.6 and I have a string which contains a number of punctuation characters I'd like to strip out. Now I've looked at using the string.punctuation() function but unfortunately, I want to strip out all punctuation characters except fullstops and dashes. In total, there are only a total of 5 punctuation marks I'd like to strip out - ()\"'

Any suggestions? I'd like this to be the most efficient way.

Thanks


Solution

  • You can use str.translate(table[, deletechars]) with table set to None, which will result in all characters from deletechars being removed from the string:

    s.translate(None, r"()\"'")
    

    Some examples:

    >>> "\"hello\" '(world)'".translate(None, r"()\"'")
    'hello world'
    >>> "a'b c\"d e(f g)h i\\j".translate(None, r"()\"'")
    'ab cd ef gh ij'