如何用python判断字符串包含多个字符串中的一个或多个

2022-07-27,,,,

开发过程中,常常需要判断字符串是否存在指定的关键词或排除词,如果设置了多个关键词,往往通过串联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

本文地址:https://blog.csdn.net/weixin_42445362/article/details/109819677

《如何用python判断字符串包含多个字符串中的一个或多个.doc》

下载本文的Word格式文档,以方便收藏与打印。