if "ABCD" in "xxxxABCDyyyy":
# whatever
INSTANCETYPE_STRING=self.machine_type
cpu_base_set = {"SMALL": 1, "MEDIUM": 2, "LARGE": 4}
for typeKey in cpu_base_set.keys():
if typeKey in INSTANCETYPE_STRING:
cpu_base = cpu_base_set[typeKey]
type_base = typeKey
a = ['a', 'b', 'c']
str = "a123"
if any(x in str for x in a):
print "some of the strings found in str"
>>> try :
... "xxxxABCDyyyy".index("test")
... except ValueError:
... print "not found"
... else:
... print "found"
...
not found
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
... print "found"
...
found
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
... print "found"
...
found
在Does Python have a string 'contains' substring method?问答中,有人对比了不同方法的效率,in
函数速度最快,find
其次,index
最慢。
import timeit
def in_(s, other):
return other in s
def contains(s, other):
return s.__contains__(other)
def find(s, other):
return s.find(other) != -1
def index(s, other):
try:
s.index(other)
except ValueError:
return False
else:
return True
perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
}
>>> perf_dict
{'in:True': 0.16450627865128808,
'in:False': 0.1609668098178645,
'__contains__:True': 0.24355481654697542,
'__contains__:False': 0.24382793854783813,
'find:True': 0.3067379407923454,
'find:False': 0.29860888058124146,
'index:True': 0.29647137792585454,
'index:False': 0.5502287584545229}