-1

(examples using python 3.8 on Ubuntu Linux 20.4 64Bit):

>>> a="/get/todo.dat"
>>> b="/get/"
>>> a.lstrip(b)
'odo.dat'

expected:
'todo.dat'

even worse:

expected answer in each case:
'0018.dat'

# first test of lstrip()
>>> name='data/rwl3_v001_Data0018.dat'
>>> mask='data/rwl3_v001_Data'
>>> name.lstrip(mask)
'8.dat'

# strip() should return the same answer:
>>> name.strip(mask)
'8.'

while '/t' might be misinterpreted maybe as tab '\t' (?) the second example puzzles me even more.

Any Ideas what happens? Help appreciated. Of course I could write a function, but is there something to know about strings and strip?

peets
  • 393
  • 1
  • 4
  • 13
  • 2
    `strip` accepts a list/iterable of the characters to remove, **not** a string – mozway Nov 12 '21 at 05:52
  • 1
    `strip` removes all the occurrences of the provided iterable. – Mushif Ali Nawaz Nov 12 '21 at 05:53
  • you can use regex or `find` method of string – Prakash Dahal Nov 12 '21 at 05:55
  • A workable solution to the problem using regex: `re.sub('^' + re.escape(mask), '', name)` for lstrip, `re.sub(re.escape(mask) + '$', '', name)` for rstrip – Green Cloak Guy Nov 12 '21 at 05:55
  • 1
    Next time, first check the [documentation on the method](https://docs.python.org/3/library/stdtypes.html#str.lstrip) you're using, which in this case happens to suggest [the correct function](https://docs.python.org/3/library/stdtypes.html#str.removeprefix) for what you're trying to do. – TigerhawkT3 Nov 12 '21 at 05:58

1 Answers1

1

strip accepts a list/iterable of the characters to remove, not a string.

Here you request to remove all /, g, e, t from both ends of a.

Use split instead: a.rsplit('/')[-1], or a dedicated library to parse/handle paths.

mozway
  • 194,879
  • 13
  • 39
  • 75