342332 发表于 2016-8-11 10:02:14

python any和all的用法, 可以查找某些字符串是否存在

有一个长字符串, 还有一个列表, 其中有一些短字符串

查找长字符串是否包含列表中的某个字符串, 只要包含就返回True

1
2
3
4
5
6
>>> x = ["aa", "bb", "cc", "dd", "ee", "ff"]
>>> s = "ttcaceekktlffc"

>>> any((s.find(k) != -1) for k in x)
True
>>>





想要查找, 这个长字符串中是否包含那个列表中的所有字符串

1
2
>>> all((s.find(k) != -1) for k in x)
False





字符串查找和替换 的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> "tta".find("t")
0
>>> if "tta".find("t") != -1:
...   print "match."
...

>>> if "tta".find("t") == -1:
...   print "not found"
... else:
...   print "found"
...
found
>>> "tta".replace("t","mt")
'mtmta'

>>> "tta".replace("at","mt")
'tta'

>>> "tta".replace("ta","mt")
'tmt'

>>> any(x)    # x中包含 不为0或不是空字符串的元素
True
>>> all(x)    # x中所有元素都不为0, 也不是空字符串
True



页: [1]
查看完整版本: python any和all的用法, 可以查找某些字符串是否存在