How can I strip first and last double quotes?

PythonStringStrip

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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]

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

If string is always as you show:

string[1:-1]

Solution 6 - Python

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!

Solution 7 - Python

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

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

> 'Hello World'

Solution 8 - Python

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]

Solution 9 - Python

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

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

Solution 10 - Python

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.

Solution 11 - Python

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'

Solution 12 - Python

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

Solution 13 - Python

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" " "" "'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWalapaView Question on Stackoverflow
Solution 1 - PythonhoubysoftView Answer on Stackoverflow
Solution 2 - PythontgrayView Answer on Stackoverflow
Solution 3 - PythonToolmakerSteveView Answer on Stackoverflow
Solution 4 - PythonAlex MartelliView Answer on Stackoverflow
Solution 5 - PythonLarryView Answer on Stackoverflow
Solution 6 - PythonpihentagyView Answer on Stackoverflow
Solution 7 - PythonnsantanaView Answer on Stackoverflow
Solution 8 - PythonTooAngelView Answer on Stackoverflow
Solution 9 - PythonXavier GuihotView Answer on Stackoverflow
Solution 10 - PythondbnView Answer on Stackoverflow
Solution 11 - PythonRomainL.View Answer on Stackoverflow
Solution 12 - PythonSumerView Answer on Stackoverflow
Solution 13 - PythonremosuView Answer on Stackoverflow