Weird python behavior when stripping from a string

Viewed 30

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'
2 Answers

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.

The strip function removes any similar character on the sides It deletes the letters on the sides and checks again the sides

examples:

>>> s = '121'
>>> s.strip('1')
'2'
>>> s.strip('2')
'121'
>>> 
>>> s.strip('12')
''
>>> 
>>> 
Related