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

问题:如何删除第一双和最后一个双引号?

我想从中删除双引号:

string = '"" " " ""\\1" " "" ""'

获得:

string = '" " " ""\\1" " "" "'

我试图用rstriplstripstrip('[^\"]|[\"$]')但没有奏效。

我怎样才能做到这一点?

I want to strip double quotes from:

string = '"" " " ""\\1" " "" ""'

to obtain:

string = '" " " ""\\1" " "" "'

I tried to use rstrip, lstrip and strip('[^\"]|[\"$]') but it did not work.

How can I do this?


回答 0

如果您要去除的引号总是像您所说的那样“第一和最后”,那么您可以简单地使用:

string = string[1:-1]

If the quotes you want to strip are always going to be “first and last” as you said, then you could simply use:

string = string[1:-1]


回答 1

如果您不能假设您处理的所有字符串都带有双引号,则可以使用如下所示的内容:

if string.startswith('"') and string.endswith('"'):
    string = string[1:-1]

编辑:

我确定您只是string在此处用作示例的变量名,并且在您的真实代码中它具有有用的名称,但是我不得不警告您string在标准库中有一个名为模块的模块。它不会自动加载,但是如果您曾经使用过,请import string确保您的变量不会使其黯然失色。

If you can’t assume that all the strings you process have double quotes you can use something like this:

if string.startswith('"') and string.endswith('"'):
    string = string[1:-1]

Edit:

I’m sure that you just used string as the variable name for exemplification here and in your real code it has a useful name, but I feel obliged to warn you that there is a module named string in the standard libraries. It’s not loaded automatically, but if you ever use import string make sure your variable doesn’t eclipse it.


回答 2

要删除第一个和最后符,并且仅在所讨论的字符为双引号的情况下,才分别删除:

import re

s = re.sub(r'^"|"$', '', s)

请注意,RE模式与您给定的RE模式不同,并且操作sub(用空格替换字符串)(“替代”)(strip是字符串方法,但与您的要求有所不同,如其他答案所示)。

To remove the first and last characters, and in each case do the removal only if the character in question is a double quote:

import re

s = re.sub(r'^"|"$', '', s)

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).


回答 3

重要说明:我正在扩展问题/答案以去除单引号或双引号。我将问题解释为必须同时存在两个引号,并且两个引号都必须匹配才能执行删除操作。否则,字符串将保持不变。

要“取消引用”字符串表示形式,该字符串表示形式周围可能带有单引号或双引号(这是@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

说明:

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

IMPORTANT: I’m extending the question/answer to strip either single or double quotes. And I interpret the question to mean that BOTH quotes must be present, and matching, to perform the strip. Otherwise, the string is returned unchanged.

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, return the string unchanged.
    """
    if (s[0] == s[-1]) and s.startswith(("'", '"')):
        return s[1:-1]
    return s

Explanation:

startswith can take a tuple, to match any of several alternatives. The reason for the DOUBLED parentheses (( and )) is so that we pass ONE parameter ("'", '"') to startswith(), to specify the permitted prefixes, rather than TWO parameters "'" and '"', which would be interpreted as a prefix and an (invalid) start position.

s[-1] is the last character in the string.

Testing:

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"

(For me, regex expressions are non-obvious to read, so I didn’t try to extend @Alex’s answer.)


回答 4

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

string[1:-1]

If string is always as you show:

string[1:-1]

回答 5

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

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

[…]

chars参数不是前缀或后缀;而是删除其值的所有组合:

因此,该参数不是正则表达式。

>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '
>>> 

注意,这并不是您所要求的,因为它在字符串的两端都使用了多个引号!

Almost done. Quoting from http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip

The chars argument is a string specifying the set of characters to be removed.

[…]

The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

So the argument is not a regexp.

>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '
>>> 

Note, that this is not exactly what you requested, because it eats multiple quotes from both end of the string!


回答 6

如果您确定要删除的开头和结尾处有一个“,请执行以下操作:

string = string[1:len(string)-1]

要么

string = string[1:-1]

If you are sure there is a ” at the beginning and at the end, which you want to remove, just do:

string = string[1:len(string)-1]

or

string = string[1:-1]

回答 7

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

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

> 'Hello World'

Remove a determinated string from start and end from a string.

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

> 'Hello World'

回答 8

我有一些代码需要去除单引号或双引号,而我不能简单地ast.literal_eval。

if len(arg) > 1 and arg[0] in ('"\'') and arg[-1] == arg[0]:
    arg = arg[1:-1]

这类似于ToolmakerSteve的答案,但是它允许长度为0的字符串,并且不能将单个字符"转换为空字符串。

I have some code that needs to strip single or double quotes, and I can’t simply ast.literal_eval it.

if len(arg) > 1 and arg[0] in ('"\'') and arg[-1] == arg[0]:
    arg = arg[1:-1]

This is similar to ToolmakerSteve’s answer, but it allows 0 length strings, and doesn’t turn the single character " into an empty string.


回答 9

在您的示例中,您可以使用地带,但必须提供空间

string = '"" " " ""\\1" " "" ""'
string.strip('" ')  # output '\\1'

注意输出中的\是字符串输出的标准python引号

您的变量的值为’\\ 1′

in your example you could use strip but you have to provide the space

string = '"" " " ""\\1" " "" ""'
string.strip('" ')  # output '\\1'

note the \’ in the output is the standard python quotes for string output

the value of your variable is ‘\\1’


回答 10

下面的函数将去除空的spces并返回不带引号的字符串。如果没有引号,它将返回相同的字符串(剥离)

def removeQuote(str):
str = str.strip()
if re.search("^[\'\"].*[\'\"]$",str):
    str = str[1:-1]
    print("Removed Quotes",str)
else:
    print("Same String",str)
return str

Below function will strip the empty spces and return the strings without quotes. If there are no quotes then it will return same string(stripped)

def removeQuote(str):
str = str.strip()
if re.search("^[\'\"].*[\'\"]$",str):
    str = str[1:-1]
    print("Removed Quotes",str)
else:
    print("Same String",str)
return str

回答 11

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

'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'

Starting in Python 3.9, you can use removeprefix and removesuffix:

'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'

回答 12

在字符串中找到第一个和最后一个“的位置

>>> s = '"" " " ""\\1" " "" ""'
>>> l = s.find('"')
>>> r = s.rfind('"')

>>> s[l+1:r]
'" " " ""\\1" " "" "'

find the position of the first and the last ” in your string

>>> s = '"" " " ""\\1" " "" ""'
>>> l = s.find('"')
>>> r = s.rfind('"')

>>> s[l+1:r]
'" " " ""\\1" " "" "'