判断字符串包含多个字符串中的一个或多个


开发过程中,常常需要判断字符串是否存在指定的关键词或排除词,如果设置了多个关键词,往往通过串联and条件或借助for循环做判断,有没有更优雅的方法呢?

判断一个字符串含有某个字符串中

p = "Tom is a boy,Lucy is a girl,they all like english!"
w= 'Tom'

print(w in p)
>>>True
print(p.find(w) > -1)
>>>True

判断一个字符串含有多个字符串中的任意一个

p = "Tom is a boy,Lucy is a girl,they all like english!"
keywords= 'Tom,Lucy'
excludes = ['english','math']
print(any([w in p and w for w in keywords.split(',')]))
>>>True
print(any(e in p for e in excludes))
>>>True

判断一个字符串含有多个字符串

p = "Tom is a boy,Lucy is a girl,they all like english!"
keywords= 'Tom,Lucy'
filters= ["boy","like"]
print(all(f in p for f in filters))
>>>True
print(all([w in p and w for w in keywords.split(',')]))
>>>True

计算一个字符串含有指定字符串的数量

p = "Tom is a boy,Lucy is a girl,Tom like math and Lucy like english!"
keywords= 'english,math,history,laws'
print sum([1 if w in p and w else 0 for w in keywords.split(',')])
>>>2


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM