Jason Friedman wrote: > $ python > Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) > [GCC 4.4.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> "x.vsd-dir".rstrip("-dir") > 'x.vs' > > I expected 'x.vsd' as a return value.
This is kind of similiar to the question, that I posted recently. "nicer way to remove prefix of a string if it exists" if you want to remove '-dir' at the end of the string if it exists and leave the string as it is if it is not followed by '-dir', then you could do: def rmv_suffix(suffix,txt): if txt.endswith(suffix): return txt[:-len(suffix)] return txt >>> rmv_suffix('-dir','abcd') 'abcd' >>> rmv_suffix('-dir','abcd-dir') 'abcd' >>> rmv_suffix('-dir','abcd-dir-and then more') 'abcd-dir-and then more' >>> the other solution would involve regular expressions: import re >>> re.sub('-dir$','','abcd') 'abcd' >>> re.sub('-dir$','','abcd-dir') 'abcd' >>> re.sub('-dir$','','abcd-dirand more') 'abcd-dirand more' >>> -- http://mail.python.org/mailman/listinfo/python-list