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).
To "dequote" a string representation, that might have either single or double quotes around it (this is an extension of @tgray's answer):
def dequote(s):
"""
If a string has single or double quotes around it, remove them.
Make sure the pair of quotes match.
If a matching pair of quotes is not found,
or there are less than 2 characters, return the string unchanged.
"""
if (len(s) >= 2 and s[0] == s[-1]) and s.startswith(("'", '"')):
return s[1:-1]
return s
Explanation:
startswith可以采用元组,以匹配多个备选方案中的任何一个。使用双括号 ((和 ))的原因是,我们将 ONE 参数 ("'", '"')传递给 startswith(),以指定允许的前缀,而不是将两个参数 "'"和 '"'解释为前缀和(无效的)起始位置。