__peter__ at web.de
Tue Sep 23 00:58:07 CEST 2003
> I have this problem with string.rstrip
> Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import string
>>>> mystr = "test.txt"
>>>> mystr = string.rstrip(mystr, ".txt")
>>>> print mystr
> The last 't' was stripped. Is this fixed or documented anywhere? it
> works for other cases, but this one seems to give me a weird result.
There are several issues with your code. The preferred way to invoke
rstrip() is now as a method, so
>>> mystr = "test.txt"
Why's that? Think of the argument of rstrip() as a character set rather than
a string; characters are removed from the end of mystr as long as they are
in [".", "t", "x"].
To remove an arbitrary suffix you can write your own function:
>>> def removeSuffix(s, suffix):
... if s.endswith(suffix):
... return s[:-len(suffix)]
... return s
>>> removeSuffix(mystr, ".txt")
However, I guess that what you really want is to remove the filename
>>> import os
This returns both parts of the string and thus gives you the chance to check
if the extension is really what you expected.
One caveat: only the last extension is cut off the filename.
More information about the Python-list