开发过程中,常常需要判断字符串是否存在指定的关键词或排除词,如果设置了多个关键词,往往通过串联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
posted on 2021-01-21 21:41  math98  阅读(4075)  评论(0)    收藏  举报