繁体   English   中英

检查字符串是否包含任何列表元素

[英]Check if string contains any list element

所以我正在做一个列表的 for 循环。 每一个字符串,我都想 .find,但不是 .find 一个字符串的一个项目,我想检查该字符串是否有我的列表中的任何内容。

例如。

checkfor = ['this','that','or the other'] 

然后做

string.find(checkfor) 什么的,所以我想这样做:

if email.find(anything in my checkforlist) == -1:
    do action

我想检查该字符串中是否有列表中的任何内容

Python有in为。

for s in checkfor:
    if s in email:
        # do action 

您可以尝试使用列表理解来完成此操作。

occurrences = [i for i, x in enumerate(email) if x =='this']

使用in子句:

If checkfor not in email:
    do_some_thing()

如果您只想知道列表中是否至少有一个值存在于字符串中,那么一种简单的方法是:

any(email.find(check) > -1 for check in checkfor)

如果你想检查所有这些都存在于字符串中,那么做

all(email.find(check) > -1 for check in checkfor)

或者,如果您想要在字符串中匹配的确切值,您可以执行以下操作:

matches = [match for match in checkfor if email.find(match) > -1]

我更愿意使用:

check in email

超过

email.find(check) > -1

但我想这取决于你的用例(上面的例子可能会用in运算符看起来更好)。

根据您的情况,您可能更喜欢使用正则表达式,但我不会在这里讨论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM