Hello, I want to strip double quotes from

string = '"" " " ""\\1" " "" ""'

to become

string = '" " " ""\\1" " "" "'

I try to use rstrip, lstrip and strip('[^\"]|[\"$]') but it not work How can I do? sorry for my english. Thank for help me.

+4  A: 

If the quotes you want to strip are always going to be "first and last" as you said, then you could simply use:

string = string[1:-1]

+1  A: 

If string is always as you show:


If you are sure there is a " at the beginning and at the end, which you want to remove, just do:

string = string[1:len(string)-1]


string = string[1:-1]
+3  A: 

If you can't assume that all the strings you process have double quotes you can use something like this:

if string.startswith('"') and string.endswith('"'):
    string = string[1:-1]


I'm sure that you just used string as the variable name for exemplification here and in your real code it has a useful name, but I feel obliged to warn you that there is a module named string in the standard libraries. It's not loaded automatically, but if you ever use import string make sure your variable doesn't eclipse it.


To remove the first and last characters, and in each case do the removal only if the character in question is a double quote:

import re

s = re.sub(r'^"|"$', '', s)

Note that the RE pattern is different than the one you had given, and the operation is sub ("substitute") with an empty replacement string (strip is a string method but does something pretty different from your requirements, as other answers have indicated).

Alex Martelli
Using a RE here is overkill IMHO. I prefer the solution with `startsWith`.
Lots of Pythonistas have similar reactions to REs, which are really unjustified -- REs are quite speedy. Plus, the solution you "prefer", as posted, does something completely different (removes first and last char only if **both** are double-quotes -- which seems different from the OP's specs) -- if leading and trailing quotes (when present) need be removed independently, that solution becomes a 4-statements, 2-conditionals block -- now **that**'s overkill compared to a single, faster expression for the same job!-)
Alex Martelli

find the position of the first and the last " in your string

>>> s = '"" " " ""\\1" " "" ""'
>>> l = s.find('"')
>>> r = s.rfind('"')

>>> s[l+1:r]
'" " " ""\\1" " "" "'

Almost done. Quoting from

The chars argument is a string specifying the set of characters to be removed.


The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

So the argument is not a regexp.

>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '

Note, that this is not exactly what you requested, because it eats multiple quotes from both end of the string!