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>