如何移除首尾双引号?
我想去掉以下内容中的双引号:
string = '"" " " ""\\1" " "" ""'
想要得到:
string = '" " " ""\\1" " "" "'
我试过用 rstrip
、lstrip
和 strip('[^\"]|[\"$]')
,但是都没有成功。
我该怎么做呢?
13 个回答
58
重要提示:我在这个问题/答案中扩展了内容,以便去掉单引号或双引号。我理解这个问题的意思是,只有当两种引号都存在并且匹配时,才能进行去掉操作。否则,字符串将保持不变。
要“去引号”一个可能被单引号或双引号包围的字符串(这是对@tgray回答的扩展):
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
解释:
startswith
可以接受一个元组,这样就可以匹配多个选项。这里使用了双重括号((
和))
,是为了将一个参数("'", '"')
传递给startswith()
,这样可以指定允许的前缀,而不是传递两个参数"'"
和'"'
,后者会被理解为一个前缀和一个(无效的)起始位置。
s[-1]
表示字符串中的最后一个字符。
测试:
print( dequote("\"he\"l'lo\"") )
print( dequote("'he\"l'lo'") )
print( dequote("he\"l'lo") )
print( dequote("'he\"l'lo\"") )
=>
he"l'lo
he"l'lo
he"l'lo
'he"l'lo"
(对我来说,正则表达式不太容易阅读,所以我没有尝试扩展@Alex的回答。)
115
如果你不能假设你处理的所有字符串都有双引号,你可以使用类似下面的代码:
if string.startswith('"') and string.endswith('"'):
string = string[1:-1]
补充说明:
我相信你在这里用 string
作为变量名只是为了举例,而在你真正的代码中,它应该有个有用的名字。不过我还是要提醒你,标准库中有一个叫做 string
的模块。这个模块不会自动加载,但如果你使用 import string
的话,确保你的变量名不会和它冲突。
217
如果你想去掉的引号总是出现在字符串的“开头和结尾”,那么你可以简单地使用:
string = string[1:-1]