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.
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.
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]
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]
or
string = string[1:-1]
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]
Edit:
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).
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 http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip
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!