2016-07-26 10 views
-1

例えばstrip()関数の後ろにpythonのスライス表記法の後ろにあるメカニズムは何ですか?

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

出力:ここ

hell 
lo worl 

ストリップ()関数オブジェクトです。したがって、パラメータを取るか、ドット表記法を使用して別のオブジェクトを続ける必要があります。しかし、関数が単純にスライス表記法に従うことはどのように可能ですか?ストリップ()とスライシングはここでどのように連携しますか?この形式をサポートする構文規則は何ですか?そう[: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 

+2

いいえ、 'strip()'は関数オブジェクトではありません。そのメソッド*の戻り値です。これはまったく別の文字列です。ここには、先頭または末尾の空白がないため、元の文字列とまったく同じです。 –

+0

"strip()は関数オブジェクトです"いいえ、それはありません。それは文字列です。それを試してみてください。これは、その文字列の空白を取り除いて新しい文字列を生成し、それをスライスするだけです。 – TigerhawkT3

答えて

2

Pythonは_result = sentence.strip()[:4]として、いくつかの別々の手順を実行します。

ここではstr.strip()コールについて特別なことはありません。別の文字列、値sentenceの除外版を返します。このメソッドは引数を渡すことなく正常に動作します。 documentation for that methodから:

省略した場合

またはNone、空白文字を除去する引数のデフォルト文字。

ここで引数を渡す必要はありません。 "hello world"には先頭または末尾の空白がないように、まったく同じストリングを返しsentence.strip()本具体例で

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

のでsentence.strip()[:4]の出力はsentence[:4]と全く同じである。

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

の出力で混乱しているように見えますが、ちょうど属性の検索。 sentence.strip(呼び出しなし)は、組み込みメソッドオブジェクトを生成します。

>>> sentence.strip 
<built-in method strip of str object at 0x102177a80> 
+0

だから簡単な説明。本当にありがとう。 @MartijnPieters。 –

関連する問題