Wal*_*apa 94 python string strip
我想从中删除双引号
string = '"" " " ""\\1" " "" ""'
Run Code Online (Sandbox Code Playgroud)
成为
string = '" " " ""\\1" " "" "'
Run Code Online (Sandbox Code Playgroud)
我试图用rstrip,lstrip并strip('[^\"]|[\"$]')但没有奏效.
我怎样才能做到这一点?感谢你们对我的帮助.
tgr*_*ray 86
如果您不能假设您处理的所有字符串都有双引号,您可以使用以下内容:
if string.startswith('"') and string.endswith('"'):
string = string[1:-1]
Run Code Online (Sandbox Code Playgroud)
编辑:
我确定你刚才用作string示例的变量名称,在你的实际代码中它有一个有用的名称,但我觉得有必要警告你string标准库中有一个模块.它没有自动加载,但是如果你曾经使用过,请import string确保你的变量没有遮挡它.
Ale*_*lli 42
删除第一个和最后一个字符,并且在每种情况下仅在相关字符为双引号时才执行删除:
import re
s = re.sub(r'^"|"$', '', s)
Run Code Online (Sandbox Code Playgroud)
请注意,RE模式与您给出的模式不同,操作是sub("替换"),带有一个空的替换字符串(strip是一种字符串方法,但与您的要求有很大不同,正如其他答案所示).
Too*_*eve 39
重要提示:我正在扩展问题/答案,以删除单引号或双引号.我解释这个问题意味着BOTH引号必须存在并匹配才能执行条带.否则,字符串将保持不变.
要"取消引用"一个字符串表示,它可能有单引号或双引号(这是@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, return the string unchanged.
"""
if (s[0] == s[-1]) and s.startswith(("'", '"')):
return s[1:-1]
return s
Run Code Online (Sandbox Code Playgroud)
说明:
startswith可以采取一个元组,以匹配几个替代品中的任何一个.的原因倍增括号((和))是使得我们通过一个参数("'", '"')来startswith(),以指定允许的前缀,而不是两个参数"'"和'"',这将被解释为一个前缀和(无效的)的开始位置.
s[-1] 是字符串中的最后一个字符.
测试:
print( dequote("\"he\"l'lo\"") )
print( dequote("'he\"l'lo'") )
print( dequote("he\"l'lo") )
print( dequote("'he\"l'lo\"") )
Run Code Online (Sandbox Code Playgroud)
=>
he"l'lo
he"l'lo
he"l'lo
'he"l'lo"
Run Code Online (Sandbox Code Playgroud)
(对我来说,正则表达式是不明显的,所以我没有尝试扩展@Alex的答案.)
几乎完成了.引自http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip
chars参数是一个字符串,指定要删除的字符集.
[...]
chars参数不是前缀或后缀; 相反,它的所有值组合都被剥离:
所以论证不是正则表达式.
>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '
>>>
Run Code Online (Sandbox Code Playgroud)
请注意,这并不是您所要求的,因为它会从字符串的两端吃掉多个引号!
从字符串的开头和结尾删除确定的字符串。
s = '""Hello World""'
s.strip('""')
> 'Hello World'
Run Code Online (Sandbox Code Playgroud)
从 开始Python 3.9,您可以使用removeprefix和removesuffix:
'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'
Run Code Online (Sandbox Code Playgroud)