-2
>>> y = 'This is string, should be without commas, but is not working'
>>> y = x.strip(",")
>>> y
'This is string, should be without commas, but is not working'

I want to remove commas from this is string but as showed above strip method does not want to work.

  • 2
    As per [the documentation](https://docs.python.org/3/library/stdtypes.html#str.strip): ‘str.strip([chars]) Return a copy of the string with the **leading and trailing** characters removed.’ (emphasis mine). – Biffen Nov 07 '20 at 10:07
  • 1
    Does this answer your question? [How to delete a character from a string using Python](https://stackoverflow.com/questions/3559559/how-to-delete-a-character-from-a-string-using-python) – khelwood Nov 07 '20 at 10:11
  • But at this example: https://www.w3schools.com/python/trypython.asp?filename=demo_ref_string_strip2 characters in a middle string were also removed. – Ziggy Witkowski Nov 07 '20 at 10:22
  • 2
    @ZiggyWitkowski They were not. Only characters leading and trailing the non-stripped characters "banana" were removed. – MisterMiyagi Nov 07 '20 at 10:23

2 Answers2

1

The strip() function removes only leading and trailing characters. And because you gave it a comma as a parameter, it will only remove leading and trailing commas.

To remove all commas from a string, you can use the replace() function. So your second line will become:

y = x.replace(",", "")
Biffen
  • 5,791
  • 5
  • 29
  • 34
Bram Dekker
  • 646
  • 5
  • 19
1

The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed). For example, on your work case strip() would work on something like:

y = ',This is string, should be without commas, but is not working ,'
x = y.strip(',')
print(x)
This is string, should be without commas, but is not working

This will get you what you need:

y = 'This is string, should be without commas, but is not working'
x = y.replace(',','')

Which outputs:

print(x)
This is string should be without commas but is not working
sophocles
  • 11,440
  • 3
  • 12
  • 27
  • It's strange and getting me confused because: 'code' txt = ",,,,,rrttggs.....sbananas...s.rrr" x = txt.strip(",s.grt") print(x)'code' Output prints "banana" only. – Ziggy Witkowski Nov 07 '20 at 10:39