您的位置:首页 > 编程语言 > Python开发

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

2016-08-10 11:12 597 查看
有一个长字符串, 还有一个列表, 其中有一些短字符串

查找长字符串是否包含列表中的某个字符串, 只要包含就返回True
>>> x = ["aa", "bb", "cc", "dd", "ee", "ff"]
>>> s = "ttcaceekktlffc"

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


想要查找, 这个长字符串中是否包含那个列表中的所有字符串
>>> all((s.find(k) != -1) for k in x)
False


字符串查找和替换 的用法
>>> "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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐