-2

Need help to strip double quotes from the variable a

>>> a
' "AZ-EDH"'

when following command is executed then only last double quotes are stripped

>>> a.strip('"')
' "AZ-EDH'

whereas when any of the following command is executed then both spaces & double quotes are stripped.

>>> a.strip('" ')
'AZ-EDH'

>>> a.strip(' " ')
'AZ-EDH'

>>> a.strip(' "')
'AZ-EDH'

What am I missing here?

Joel Divekar
  • 187
  • 1
  • 4
  • 19
  • 1
    You're confusing `str.strip` and `str.replace`. `str.strip` removes *leading* and *trailing* characters (usually whitespace). What you want is probably `a.replace('"', '')` – Abirbhav G. Aug 07 '23 at 09:39
  • From Python docs - "`str.strip([chars])` - Return a copy of the string with the leading and trailing characters removed." Why do you expect it to remove anything in the middle? – matszwecja Aug 07 '23 at 09:39

5 Answers5

2

str.strip() only removes leading/trailing characters, if you want to remove all occurrences of a character, use str.replace() instead:

>>> a=' "AZ-EDH"'
>>> a.replace('"', '')
' AZ-EDH'
>>>
Tzane
  • 2,752
  • 1
  • 10
  • 21
2

Python str.strip() only removes leading and trailing characters.

The first " in ' "AZ-EDH"' is not a leading character because of the space.

The optional parameter is a set of characters to remove. This means your examples of ' "', '" ', ' " ' are identical in meaning. They remove all leading " and .

https://python-reference.readthedocs.io/en/latest/docs/str/strip.html

You might be looking for str.replace('"', '').

https://python-reference.readthedocs.io/en/latest/docs/str/replace.html

FLWE
  • 214
  • 2
  • 5
1
A = '"AZ-EDH"'
>>>'"AZ-EDH"'

A.replace('"', '')
>>>'AZ-EDH'

.replace function in python would do the trick.

1

as stated in str.strip method

strip(self, chars=None, /)
    Return a copy of the string with leading and trailing whitespace removed.

    If chars is given and not None, remove characters in chars instead.

for the case:

>>> a.strip('"')
' "AZ-EDH'

you have provided the character " only , so it wont strip space from start. and this resulting into "AZ-EDH

and in other cases you have provided the space also, this you are getting the desired result.

sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

Try using replace instead:

a.replace(chr(34),'')

Kurt Moan
  • 11
  • 3