views:

88

answers:

4
>>> 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 does the 'g' of '.org' is gone?

+5  A: 

strip removes any of the characters ., g and z from the beginning and end of the string.

Deniz Dogan
+6  A: 

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
`'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
@Wayne: doesn't the `[]` mean "optional" in the doc?
KennyTM
@Kenny: it might, I have no idea - but if it does, I'd consider that a bug in the documentation.
Wayne Werner
@Wayne: It's used as "optional" everywhere e.g. http://docs.python.org/py3k/library/functions.html#range.
KennyTM
@Kenny: 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
+1  A: 

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
+1  A: 

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