Strange Python strip() behavior

Question:

I don’t understand why the strip() function returns the way it does below. I want to strip() the last occurence of Axyx. I got around it by using rstrip(‘Axyx’) but what’s the explanation for the following?

>>>"Abcd Efgh Axyx".strip('Axyx')
'bcd Efgh '
Asked By: user2399453

||

Answers:

The string passed to strip is treated as a bunch of characters, not a string. Thus, strip('Axyx') means “strip occurrences of A, x, or y from either end of the string”.

If you actually want to strip a prefix or suffix, you’d have to write that logic yourself. For example:

s = 'Abcd Efgh Axyx'
if s.endswith('Axyx'):
    s = s[:-len('Axyx')]
Answered By: Ismail Badawi

Because strip() returns a copy of the string that you provided without the characters that you gave as input.
For example:
“12345”.strip(‘123′) returns: ’45’.
So, strip() does not remove words or something but removes all the characters that the string that you give as input has, both from the end and the beginning of the string that you want to strip.

Answered By: zuko32
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.