-1

For example

sentence = "hello world"
stripped1 = sentence.strip()[:4]
stripped2 = sentence.strip()[3:8]
print (stripped1)
print (stripped2)

Output:

hell
lo worl

Here strip( ) is a function object. So it should either take parameters or be followed by another object using dot notation. But how is it possible that the function is simply followed by slice notation ? How does strip( ) and slicing work together here ? what is the syntax rule supporting this format ?

Uchiha Madara
  • 984
  • 5
  • 16
  • 35
  • 2
    No, `strip()` is not a function object. It is the *return value of that method*. That's just another string, here exactly equal to the original as there is no leading or trailing whitespace. – Martijn Pieters Jul 26 '16 at 09:57
  • "strip( ) is a function object" No it isn't. It's a string. Try it. This is just stripping the whitespace off of that string to produce a new, stripped string, and then slicing it. – TigerhawkT3 Jul 26 '16 at 09:57

1 Answers1

2

Python executes _result = sentence.strip()[:4] as several separate steps:

_result = sentence       # look up the object "sentence" references
_result = _result.strip  # attribute lookup on the object found
_result = _result()      # call the result of the attribute lookup
_result = _result[:4]    # slice the result of the call
stripped1 = _result      # store the result of the slice in stripped1

so [:4] is just more syntax, just like a () call, that can be applied to the outcome of another expression.

There is nothing special about the str.strip() call here, it just returns another string, the stripped version of the value of sentence. The method works fine without passing in any arguments; from the documentation for that method:

If omitted or None, the chars argument defaults to removing whitespace.

so there is no requirement here to pass in arguments.

In this specific example, sentence.strip() returns the exact same string, as there is no leading or trailing whitespace in "hello world":

>>> sentence = "hello world"
>>> sentence.strip()
'hello world'
>>> sentence.strip() == sentence
True

so the output of sentence.strip()[:4] is exactly the same as for sentence[:4]:

>>> sentence.strip()[:4] == sentence[:4]
True

You appear to have missed the call there, as you appear to be confused by the output of just the attribute lookup; sentence.strip (no call), produces a built-in method object:

>>> sentence.strip
<built-in method strip of str object at 0x102177a80>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343