Hank wrote: > Hi, > > I have this problem with string.rstrip > > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import string >>>> mystr = "test.txt" >>>> mystr = string.rstrip(mystr, ".txt") >>>> print mystr > tes > > 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" >>> mystr.rstrip(".txt") 'tes' 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") 'test' However, I guess that what you really want is to remove the filename extension: >>> import os >>> os.path.splitext(mystr) ('test', '.txt') >>> os.path.splitext(mystr)[0] 'test' 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. >>> os.path.splitext("test.tar.gz") ('test.tar', '.gz') Peter
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4