的Python執行_result = sentence.strip()[:4]
幾個單獨步驟:
_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
所以[:4]
只是以上語法,就像一個()
呼叫,可被應用到另一種表達的結果。
這裏調用str.strip()
沒什麼特別的,它只是返回另一個字符串,即sentence
的值的剝離版本。該方法工作正常,沒有傳入任何參數;從documentation for that method:
如果省略或None
,所述字符參數默認爲去除空格。
所以這裏沒有要求傳遞參數。
在這個具體的例子中,sentence.strip()
返回確切相同的字符串,因爲是在"hello world"
沒有前導或尾隨空白:
>>> sentence = "hello world"
>>> sentence.strip()
'hello world'
>>> sentence.strip() == sentence
True
這樣的sentence.strip()[:4]
輸出是完全一樣爲sentence[:4]
:
>>> sentence.strip()[:4] == sentence[:4]
True
您似乎錯過了那裏的電話,因爲您似乎對的輸出感到困惑,只是屬性查找; sentence.strip
(no call),產生一個內置的方法對象:
>>> sentence.strip
<built-in method strip of str object at 0x102177a80>
不,strip()不是函數對象。它是該方法的*返回值*。這只是另一個字符串,這裏與原始字符完全相同,因爲沒有前導或尾隨空格。 –
「strip()是一個函數對象」不,它不是。這是一個字符串。嘗試一下。這只是從該字符串中刪除空白字符以產生一個新的剝離字符串,然後對其進行分片。 – TigerhawkT3