2017-04-13 74 views
5

很奇怪地看到使用「在乙方對str中」語法的一段代碼,如:Python字符串在...語法

>>> 'test' in 'testtest' in 'testtesttest' 
True 
>>> 'test' in 'testtest' in 'tb3' 
False 
>>> 'test' in 'testtesta' in 'testtesttest' 
False 
>>> 'test' in ('testtest' in 'testtesttest') 
Traceback (most recent call last): 
    File "<input>", line 1, in <module> 
    'test' in ('testtest' in 'testtesttest') 
TypeError: argument of type 'bool' is not iterable 

看來「在......在.. ''與'< ... < ...'比較類似。但一個快速谷歌並沒有引導我到正式的答案。任何幫助?從Python documentation

+0

我想你的猜測是正確的。 「C中B中的A」表示「A中B和B中C」,就像「a Organis

回答

5

官方的回答:

comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!=" 
        | "is" ["not"] | ["not"] "in" 

in關鍵字是比較操作。和「比較可以任意鏈接」。請注意,這不限於「值比較」(>==等)。

有問題的代碼檢查每個鏈是否是鏈中下一項的子串。