-1

What is causing this strange behavior???

In [41]: s = "Mr Magoo Myyopia"
In [42]: t = s.strip("Mr Magoo")
In [43]: t
Out[43]: 'yyopi'

but if I change up the contents of the string...

In [44]: s = "hello world again"
In [45]: t = s.strip("hello world")
In [46]: t
Out[46]: 'again'
anon says hello
  • 133
  • 1
  • 2
  • 10
  • `removeprefix` is method you need (py3.9+). – STerliakov Sep 24 '22 at 18:25
  • A simple removal of words, phrases or exact character sequences can be achieved using _replace_ search-string by empty-string like `replace('Mr Magoo', '')`, see [how-to-strip-a-specific-word-from-a-string](https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string) – hc_dev Sep 24 '22 at 18:31

2 Answers2

2

The docstring explains it pretty clearly:

Return a copy of the string with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.

Any and all characters given to strip() are removed from the string if they are leading or trailing. 'Mr Magoo' contains an 'a', which is also present in the 'Myyopia' part - hence it also got stripped.

'hello world' has no characters which are also present in 'again', hence it is not stripped.

strip() works with characters, not substrings.

rdas
  • 20,604
  • 6
  • 33
  • 46
  • 3
    "Any and all characters given to `strip()` are removed from the string." Clearly not, as `'yyopi'` still contains an `o`. Why: "The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars." I.e. leading strip is stopping at `y` because the char is not in `'Mr Magoo'`, and trailing strip is stopping at `i` for the same reason. – ouroboros1 Sep 24 '22 at 18:17
  • 2
    the outermost values, tysm – anon says hello Sep 24 '22 at 18:18
0

strip replaces the outermost characters, that are supplied as a string. i failed to recognize the "outermost" aspect. thanks everyone.

anon says hello
  • 133
  • 1
  • 2
  • 10