如何去掉第一个和最后一个双引号?

发布于 2024-09-06 03:10:22 字数 222 浏览 3 评论 0原文

我想从: 中删除双引号

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

以获得:

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

我尝试使用 rstrip、lstrip 和 strip('[^\"]|[\"$] ') 但它不起作用。

我该怎么做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

所有深爱都是秘密 2024-09-13 03:10:22

如果您要删除的引号始终如您所说的“第一个和最后一个”,那么您可以简单地使用:

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]

我为君王 2024-09-13 03:10:22

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

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

编辑:

我确定您刚刚使用了 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.

勿忘初心 2024-09-13 03:10:22

重要提示:我正在扩展问题/答案以去掉单引号或双引号。我将这个问题解释为两个引号都必须存在并且匹配才能执行剥离。否则,字符串原样返回。

要“取消引用”字符串表示形式,该字符串表示形式可能带有单引号或双引号(这是 @tg​​ray 答案的扩展):

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 可以采用一个元组,以匹配多个替代方案中的任何一个。使用双括号 (()) 的原因是我们将一个参数 ("'", '"') 传递给 < code>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,
    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 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.)

挽手叙旧 2024-09-13 03:10:22

要删除第一个和最后一个字符,并且在每种情况下仅当相关字符是双引号时才删除:

import re

s = re.sub(r'^"|"

请注意,RE 模式与您给出的模式不同,并且操作是 sub (“替换”)带有空替换字符串(strip 是一种字符串方法,但其功能与您的要求完全不同,正如其他答案所示)。

, '', s)

请注意,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'^"|"

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

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

烟若柳尘 2024-09-13 03:10:22

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

string[1:-1]

If string is always as you show:

string[1:-1]
蓝梦月影 2024-09-13 03:10:22

快完成了。引用自 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!

奈何桥上唱咆哮 2024-09-13 03:10:22

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

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'
缱绻入梦 2024-09-13 03:10:22

Python 3.9 开始,您可以使用 removeprefix删除后缀

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

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

'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'
嗳卜坏 2024-09-13 03:10:22

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

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]
停滞 2024-09-13 03:10:22

我有一些代码需要去掉单引号或双引号,并且我不能简单地对其进行 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.

北城挽邺 2024-09-13 03:10:22

在你的例子中你可以使用 strip 但你必须提供空格

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'

小红帽 2024-09-13 03:10:22

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

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
夏了南城 2024-09-13 03:10:22

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

>>> 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" " "" "'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文