How to check a string for specific characters? 我發現該鏈接非常有用。但是,我的代碼有什麼問題?IF中的某些單詞有什麼問題字符串中的某些單詞
string = "A17_B_C_S.txt"
if ("M.txt" and "17") in string:
print True
else:
print False
,答案永遠是
True
How to check a string for specific characters? 我發現該鏈接非常有用。但是,我的代碼有什麼問題?IF中的某些單詞有什麼問題字符串中的某些單詞
string = "A17_B_C_S.txt"
if ("M.txt" and "17") in string:
print True
else:
print False
,答案永遠是
True
這是因爲你的and
計算爲17
這是stringList
。由於短路,and
評估爲17。
>>> "M.txt" and "17"
'17'
Python的評估非空字符串值True
。因此,M.txt
的計算結果爲True
,因此表達式的值取決於返回的第二個值(17
)並在stringList
中找到。 (爲什麼?當and
與True
值執行,表達式的值取決於第二個值,如果它是False
,表達式的值是False
,否則,它的True
。)
您需要更改表達
if "M.txt" in stringList and "17" in stringList:
#...
或者使用內置的all()
if all(elem in stringList for elem in ["M.txt", "17"]):
#...
非常明確的解釋。謝謝。 – Shengen
stringList = "A17_B_C_S.txt"
if "M.txt" in stringList and "17" in stringList:
print True
else:
print False
>>>
True
('M.txt' and '17')
返回'17'
。所以你只是在測試'17' in stringList
。
>>> ('M.txt' and '17')
'17'
>>>
("M.txt" and "17")
返回"17"
,因爲它的計算結果爲(True and True)
(bool("M.txt") == True
)。因此,選擇第二個。
然後你想說if "17" in string
。
您必須逐個比較的品種:
if "M.txt" in stringList and "17" in stringList:
甚至:
if all(i in stringList for i in ("M.txt", "17")):
這是因爲
("M.txt" and "17") in string
並不意味着它可能聲音喜歡。在蟒蛇,它意味着:
測試一個值,你會得到執行布爾之間 「M.txt」和「17」的時候,是「字符串」
發現裏面您的代碼中的and
不僅執行and
運算符,還會返回最後一個術語,即"17"
。因此(「M.TXT「和‘17’)將返回‘17’,因此它實際上將只有測試,如果"17"
是在string
如果你真正想要的是:
測試,如果有」 M .TXT」字符串,也有 「字符串
17」 你必須寫:
if "M.txt" in string and "17" in string:
密切相關:如果X或Y或Z ==嗒嗒](HTTP://計算器。 com/q/15112125) –
不要使用'if some_boolean_test:print True;否則:僅在print some_boolean_test時會打印False。 –
+1這是一個常見的陷阱,當從現有的「演講」的數字移動到自己的構造而沒有完全掌握每個子元素的全部含義時,絕對合法的問題IMO – Nicolas78