1

Is there a reason why I am having this kind of string strip behavior ? Is this a bug or some string magic I am missing

# THIS IS CORRECT
>>> 'name.py'.rstrip('.py')
'name'


# THIS IS WRONG     
>>> 'namey.py'.rstrip('.py')
'name'

# TO FIX THE ABOVE I DID THE FOLLOWING
>>> 'namey.py'.rstrip('py').rstrip('.')
'namey'
DSM
  • 342,061
  • 65
  • 592
  • 494
Cobry
  • 4,348
  • 8
  • 33
  • 49

1 Answers1

1

That's because the str.rstrip() command removes each trailing character, not the whole string.

https://docs.python.org/2/library/string.html

string.rstrip(s[, chars]) Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.

This also generates same result
>>> 'nameyp.py'.rstrip('.py')
'name'

You could try str().endswith

>>> name = 'namey.py'
... if name.endswith('.py'):
...     name = name[:-3]

>>> name
'namey'

Or just str().split()

>>> 'namey.py'.split('.py')[0]
'namey'
Teddy Katayama
  • 128
  • 1
  • 9