如何删除第一个和最后一个双引号

Wal*_*apa 94 python string strip

我想从中删除双引号

string = '"" " " ""\\1" " "" ""'
Run Code Online (Sandbox Code Playgroud)

成为

string = '" " " ""\\1" " "" "'
Run Code Online (Sandbox Code Playgroud)

我试图用rstrip,lstripstrip('[^\"]|[\"$]')但没有奏效.

我怎样才能做到这一点?感谢你们对我的帮助.

hou*_*oft 176

如果你要删除的引号总是像你说的那样"先到先后",那么你可以简单地使用:

string = string[1:-1]

  • 下面这个比较安全! (2认同)

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是一种字符串方法,但与您的要求有很大不同,正如其他答案所示).

  • 许多Pythonist对RE有类似的反应,这实际上是不合理的 - RE非常快.此外,该解决方案你"喜欢",张贴,会产生完全不同的(除去第一和最后一个字符只有两个****是双引号 - 从OP的规格似乎有所不同) - 如果开头和结尾报价(当存在时)需要独立删除,该解决方案变为4个语句,2个条件块 - 现在****相比于同一个作业的单个,更快的表达式**的过度杀伤! - ) (18认同)
  • 在这里使用RE是矫枉过正的恕我直言.我更喜欢`startsWith`的解决方案. (4认同)

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的答案.)

  • 我建议处理2个字符或更少的字符串.现在,此函数可以为长度为0的字符串抛出索引超出范围的异常.此外,您可以从1个字符长的字符串中删除引号.你可以添加一个守卫,`len(s)> = 2`,或类似的东西. (4认同)
  • 如果您首先检查第一个和最后一个字符是否相同,则只需检查第一个字符是否是引号: def strip_if_quoted(name): if name[0] == name[-1] and name[0 ] in ("'", '"'): 返回名称[1:-1] (2认同)

Lar*_*rry 10

如果字符串始终如您所示:

string[1:-1]
Run Code Online (Sandbox Code Playgroud)


pih*_*agy 9

几乎完成了.引自http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip

chars参数是一个字符串,指定要删除的字符集.

[...]

chars参数不是前缀或后缀; 相反,它的所有值组合都被剥离:

所以论证不是正则表达式.

>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '
>>> 
Run Code Online (Sandbox Code Playgroud)

请注意,这并不是您所要求的,因为它会从字符串的两端吃掉多个引号!


nsa*_*ana 5

从字符串的开头和结尾删除确定的字符串。

s = '""Hello World""'
s.strip('""')

> 'Hello World'
Run Code Online (Sandbox Code Playgroud)


Xav*_*hot 5

从 开始Python 3.9,您可以使用removeprefixremovesuffix

'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'
Run Code Online (Sandbox Code Playgroud)