word="hello"
word_list="hello world"
if word in word_list:
print("True")
else:
print("False")
result:True
word="hello"
word_list=["hello world","today is sunny","happy new year"]
if word in word_list:
print("True")
else:
print("False")
# result:False
word="hello"
word_list=["hello","today is sunny","happy new year"]
if word in word_list:
print("True")
else:
print("False")
# result:True
结论:
in 字符串匹配时,为部分匹配
in 列表匹配时,为完全匹配
如何对列表中的对象进行部分匹配呢
word="hello"
word_list=["hello world","today is sunny","happy new year"]
# 方案1
result=[]
for text in str1:
if str in text:
result.append(text)
# 方案2
result = [v for v in word_list if word in v]
# 方案3
result=list(filter(lambda x: word in x, word_list))
#大小写转换
l = list(map(str.lower, l)) 映射字符串列表为小写
word1=word.lower(),word1小写 但word不变
# result:a=["hello world"]
这篇博客探讨了Python中使用'in'关键字在字符串和列表中进行匹配的不同行为。在字符串中,'in'进行部分匹配,而在列表中则需要完全匹配。针对列表的部分匹配,提出了三种解决方案:遍历、列表推导式和使用filter函数。同时,还介绍了如何通过将列表元素转换为小写来进行不区分大小写的匹配。这些技巧在文本处理和数据分析中非常实用。
1560

被折叠的 条评论
为什么被折叠?



