2016-07-26 29 views
-1

例如strip()函數後跟python中的切片符號的機制是什麼?

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

輸出:

hell 
lo worl 

這裏帶材()是一個函數對象。所以它應該採用參數或者使用點符號來跟隨另一個對象。但是這個函數怎麼可能跟着切片符號呢? strip()和切片如何在這裏一起工作?支持這種格式的語法規則是什麼?

+2

不,strip()不是函數對象。它是該方法的*返回值*。這只是另一個字符串,這裏與原始字符完全相同,因爲沒有前導或尾隨空格。 –

+0

「strip()是一個函數對象」不,它不是。這是一個字符串。嘗試一下。這只是從該字符串中刪除空白字符以產生一個新的剝離字符串,然後對其進行分片。 – TigerhawkT3

回答

2

的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> 
+0

這麼簡單的解釋。非常感謝。 @MartijnPieters。 –

相關問題