所以我正在做一个for循环的列表。每一个字符串,我想.find,而不是.find一个项目的字符串,我想检查该字符串的任何东西在我的列表中。检查字符串是否包含任何列表元素
例如。
checkfor = ['this','that','or the other']
然后做
string.find(checkfor)什么的,所以我想这样做:
if email.find(anything in my checkforlist) == -1:
do action
所以我正在做一个for循环的列表。每一个字符串,我想.find,而不是.find一个项目的字符串,我想检查该字符串的任何东西在我的列表中。检查字符串是否包含任何列表元素
例如。
checkfor = ['this','that','or the other']
然后做
string.find(checkfor)什么的,所以我想这样做:
if email.find(anything in my checkforlist) == -1:
do action
我要检查字符串中的任何东西我list
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
运算符)。
根据你的情况,你可能更喜欢使用regular expressions,但我不会在这里进入。
您是否试图找到该列表中所有内容的位置,或者您是否试图检查该列表中是否有任何内容包含在您的字符串中? –