码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-08-10 14:36:41      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:python any all 查找字符串

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


查找长字符串是否包含列表中的某个字符串, 只要包含就返回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


本文出自 “R和Python应用” 博客,请务必保留此出处http://matrix6ro.blog.51cto.com/1746429/1836439

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

标签:python any all 查找字符串

原文地址:http://matrix6ro.blog.51cto.com/1746429/1836439

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!