2011-03-29 63 views

回答

172
if "ABCD" in "xxxxABCDyyyy": 
    # whatever 
+4

這在這裏有效,但如果您測試的是非字符串,則可能不會給出預期的結果。例如。如果對字符串列表進行測試(可能在[「xxxxabcdyyyy」]中使用'if「ABCD」),這可能會失敗。 – GreenMatt 2011-03-29 15:37:56

+1

@GreenMatt如果你知道它是一個列表,只要在列表[0]中說'如果'ABCD'。 – 2016-07-20 13:08:05

27

還有其他幾種方式,除了使用 「在」 操作符(簡單)

index()

>>> try : 
... "xxxxABCDyyyy".index("test") 
... except ValueError: 
... print "not found" 
... else: 
... print "found" 
... 
not found 

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1: 
... print "found" 
... 
found 

re

>>> import re 
>>> if re.search("ABCD" , "xxxxABCDyyyy"): 
... print "found" 
... 
found 
+4

儘管最後一個需要和're.escape'調用。 – delnan 2011-03-29 13:28:27

相關問題