strip() 函数后跟 python 中的切片符号背后的机制是什么?
What is the mechanism behind strip() function followed by a slice notation in python?
例如
sentence = "hello world"
stripped1 = sentence.strip()[:4]
stripped2 = sentence.strip()[3:8]
print (stripped1)
print (stripped2)
输出:
hell
lo worl
这里的strip( ) 是一个函数对象。因此它应该采用参数或使用点表示法后跟另一个对象。但是函数后面怎么可能只是切片符号呢? strip() 和切片在这里如何协同工作?支持这种格式的语法规则是什么?
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()
调用没有什么特别的,它只是 returns 另一个字符串,sentence
值的剥离版本。该方法在不传递任何参数的情况下工作正常;来自 documentation for that method:
If omitted or None
, the chars argument defaults to removing whitespace.
所以这里不需要传参
在此特定示例中,sentence.strip()
returns 完全相同的字符串 ,因为 "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
(不调用),生成一个内置方法对象:
>>> sentence.strip
<built-in method strip of str object at 0x102177a80>
例如
sentence = "hello world"
stripped1 = sentence.strip()[:4]
stripped2 = sentence.strip()[3:8]
print (stripped1)
print (stripped2)
输出:
hell
lo worl
这里的strip( ) 是一个函数对象。因此它应该采用参数或使用点表示法后跟另一个对象。但是函数后面怎么可能只是切片符号呢? strip() 和切片在这里如何协同工作?支持这种格式的语法规则是什么?
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()
调用没有什么特别的,它只是 returns 另一个字符串,sentence
值的剥离版本。该方法在不传递任何参数的情况下工作正常;来自 documentation for that method:
If omitted or
None
, the chars argument defaults to removing whitespace.
所以这里不需要传参
在此特定示例中,sentence.strip()
returns 完全相同的字符串 ,因为 "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
(不调用),生成一个内置方法对象:
>>> sentence.strip
<built-in method strip of str object at 0x102177a80>