The simple detection would involve checking s[:1] == s[-1:] == '"'
(carefully phrasing it with slicing rather than indexing to avoid exceptions if s
is an empty string), and the conditional removal of exactly one quote from each end if one is present at both ends is
if s[:1] == s[-1:] == '"':
s = s[1:-1]
Alternatively, the approach in @Magnus's answer, as he says, removes all leading and trailing quote, and does so unconditionally; so, for example, if s
starts with three quotes but doesn't end with any (and in all sort of other weird cases, outside of your specs as stated), the snippet in my answer won't alter s
, @Magnus's will strip the three leading quotes.
"You pay your money and you take your choice"... if you don't care one way or another (i.e. you're sure that the situation where the two answers differ is "totally and utterly impossible"...), then I think @Magnus's higher-abstraction-level approach is neater (but, it's a matter of style -- both his approach and mine are correct Python solutions when you don't care about unmatched or unbalanced quotes;-).