5
>>> t1 = "abcd.org.gz"
>>> t1
'abcd.org.gz'
>>> t1.strip("g")
'abcd.org.gz'
>>> t1.strip("gz")
'abcd.org.'
>>> t1.strip(".gz")
'abcd.or'

Why is the 'g' of '.org' gone?

martineau
  • 119,623
  • 25
  • 170
  • 301
Tzury Bar Yochay
  • 8,798
  • 5
  • 49
  • 73

5 Answers5

10

strip(".gz") removes any of the characters ., g and z from the beginning and end of the string.

Manuel Selva
  • 18,554
  • 22
  • 89
  • 134
Deniz Dogan
  • 25,711
  • 35
  • 110
  • 162
9

x.strip(y) will remove all characters that appear in y from the beginning and end of x.

That means

'foo42'.strip('1234567890') == 'foo'

becuase '4' and '2' both appear in '1234567890'.


Use os.path.splitext if you want to remove the file extension.

>>> import os.path
>>> t1 = "abcd.org.gz"
>>> os.path.splitext(t1)
('abcd.org', '.gz')
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • `'abcd.org.gz'.strip('.gzor')` produces `'abcd'` -- surprisingly enough the docstring isn't too helpful unless you notice the `[]` in the `S.strip([chars])` and remember that a string is just a sequence of characters. Good explanation, and good alternative – Wayne Werner Jun 07 '10 at 16:23
  • @Wayne: doesn't the `[]` mean "optional" in the doc? – kennytm Jun 07 '10 at 16:49
  • it might, I have no idea - but if it does, I'd consider that a bug in the documentation. – Wayne Werner Jun 08 '10 at 11:02
  • @Wayne: It's used as "optional" everywhere e.g. http://docs.python.org/py3k/library/functions.html#range. – kennytm Jun 08 '10 at 11:14
  • I guess that's why I didn't notice it as suggesting a collection at first! That means the docstring for strip is ambiguous and could use some clearer wording. While the name 'chars' is suggestive, the docstring isn't clear that it uses the collection in any order from front and back - at least not to me. – Wayne Werner Jun 08 '10 at 12:42
  • @WayneWerner but it is optional - if you leave the parameter off, it defaults to a list of whitespace characters. – Mark Ransom May 27 '22 at 17:39
5

In Python 3.9, there are two new string methods .removeprefix() and .removesuffix() to remove the beginning or end of a string, respectively. Thankfully this time, the method names make it aptly clear what these methods are supposed to perform.

>>> print (sys.version)
3.9.0 
>>> t1 = "abcd.org.gz"
>>> t1.removesuffix('gz')
'abcd.org.'
>>> t1
'abcd.org.gz'
>>> t1.removesuffix('gz').removesuffix('.gz')
'abcd.org.'     # No unexpected effect from last removesuffix call
 
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
1

The argument given to strip is a set of characters to be removed, not a substring. From the docs:

The chars argument is a string specifying the set of characters to be removed.

Will McCutchen
  • 13,047
  • 3
  • 44
  • 43
1

as far as I know strip removes from the beginning or end of a string only. If you want to remove from the whole string use replace.

Richard
  • 15,152
  • 31
  • 85
  • 111