Search code examples
pythonstringstrip

Why doesn't str.strip(" London") throw an error?


I found in a textbook an example of when following works:

value = "   London"
result = str.strip(value)
print result

Now I know strip method under a different use case as value.strip(characters) where you can pass in characters you wish to remove (or just leave blank) -> e.g. value.strip("n") should just return " Londo"

I can't get my head around why the example above where the whole string is passed into a strip method as a variable (and then returns the result without whitespaces) would work? Tried chatGPT and it thinks it's incorrect and would throw a Type Error and googling around keeps referring to the use case where you can pass into the method characters you want to remove.

Anybody knows why?

Expected to get an error returned


Solution

  • In python, methods are really just functions in a class namespace. If you call the function through an instance of the class, python will convert the function to a method and will prepend a reference to the instance as the function's first argument. If you call the function through the class itself, this magic is not applied.

    When writing your own class, as in

    class Foo:
        def bar(self):
            print(self)
    

    that self that you had to write as part of the function definition is a reference to the instance object.

    If you write

    value = "   London"
    result = value.strip()
    

    python's instance rule is in effect. Python will automatically fill in self before calling str.strip.

    If you write

    str.strip(value)
    

    python's instance rule is not in effect and a self is not added automatically. But since you supplied a parameter that fits in the same place, the function will still see it as self and will work anyway.

    There is a minor wrinkle. Unlike the case of Foo.bar that is of type function, str.strip is already of type method. That's because str is implemented in C and that's how the C jump table is built. But the same rules apply.