[Python]检查是否含有指定字符串(contains)(忽略大小写,正则方式)

2021-05-09 3023点热度 0人点赞 0条评论

Python中String没有类似Java里的contains,不过可以使用string.find返回找到的下标来判断是否包含字符串:

source_string = 'abc'
contains_string = 'a'
founded_index = source_string.find(contains_string)  # 找到返回>=0 找不到返回-1
print(founded_index >= 0)  # 根据找到的index判断是否包含字符串

不过有个问题,如果我们要不要判断大小写呢(大小写不敏感),有个办法把source_string和contains_string都转成大写或者小写,然后再find

source_string = 'abc'
contains_string = 'B'
founded_index = source_string.find(contains_string)  # 返回-1
print(founded_index >= 0)  # False

founded_index = source_string.lower().find(contains_string.lower())
print(founded_index)  # 返回1

还有一个办法,利用正则表达式:

source_string = 'abc'
contains_string = 'B'
if re.search(contains_string, source_string, re.IGNORECASE):
    print("found")
else:
    print("not found")

 

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论