120

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?

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
Walapa
  • 1,201
  • 2
  • 8
  • 3
  • 6
    The correct answers are given below. As for your approach with `strip`, please note that a) this method doesn't take a regex as its argument, b) the regex you supplied wouldn't have worked anyway and c) this method strips all adjacent characters, not just one, so you would have lost two double quotes with `.strip('"')`. – Tim Pietzcker Jun 21 '10 at 14:31

13 Answers13

215

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]

houbysoft
  • 32,532
  • 24
  • 103
  • 156
111

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.

tgray
  • 8,826
  • 5
  • 36
  • 41
  • 1
    If string is '"' (just one double quote), this will remove the single character. I think this is probably not what is desired, probably Walapa wanted to only remove the double quote if it was matched. – dbn Aug 26 '16 at 00:28
56

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

ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196
  • 2
    If you first check that the first and last chars are the same, you then only need to check if the first char is a quote: def strip_if_quoted(name): if name[0] == name[-1] and name[0] in ("'", '"'): return name[1:-1] – TomOnTime Jan 24 '14 at 15:21
  • @TomOnTime: You are right, that is a good optimization. I have applied it. – ToolmakerSteve Aug 07 '14 at 01:45
  • 6
    I'd recommend handling strings that are 2 characters or less. Right now this function can throw an index out of bounds exception for a string of length 0. Additionally, you can strip a quote from a string that is 1 character long. You could add a guard, `len(s) >= 2`, or something similar. – BrennanR Dec 02 '15 at 21:20
  • excellent suggestion! Question edited to add that. – ToolmakerSteve Nov 09 '22 at 19:50
51

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

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 4
    Using a RE here is overkill IMHO. I prefer the solution with `startsWith`. – pihentagy Jun 21 '10 at 15:57
  • 25
    Lots of Pythonistas have similar reactions to REs, which are really unjustified -- REs are quite speedy. Plus, the solution you "prefer", as posted, does something completely different (removes first and last char only if **both** are double-quotes -- which seems different from the OP's specs) -- if leading and trailing quotes (when present) need be removed independently, that solution becomes a 4-statements, 2-conditionals block -- now **that**'s overkill compared to a single, faster expression for the same job!-) – Alex Martelli Jun 21 '10 at 16:51
16

If string is always as you show:

string[1:-1]
Larry
  • 314
  • 1
  • 5
8

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!

pihentagy
  • 5,975
  • 9
  • 39
  • 58
5

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

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

> 'Hello World'
nsantana
  • 1,992
  • 1
  • 16
  • 17
  • Definitely the easiest answer to implement! But why the doubled-double quotes? – Erik Knowles May 04 '23 at 21:25
  • You are right! I had to use the question example. Looking now, I figure out that this example is incorrect for this question, since it doesn't keep one double quote. – nsantana May 07 '23 at 08:59
5

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

'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
4

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]
TooAngel
  • 873
  • 6
  • 13
1

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.

dbn
  • 13,144
  • 3
  • 60
  • 86
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'

RomainL.
  • 997
  • 1
  • 10
  • 24
0

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
Sumer
  • 2,687
  • 24
  • 24
-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" " "" "'
remosu
  • 5,039
  • 1
  • 23
  • 16