在 Python 中,如何检查字符串是否不包含列表中的任何字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32121521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Python, how can I check that a string does not contain any string from a list?
提问by StringsOnFire
For example, where:
例如,其中:
list = [admin, add, swear]
st = 'siteadmin'
st
contains string admin
from list
.
st
包含admin
来自list
.
- How can I perform this check?
- How can I be informed which string from
list
was found, and if possible where (from start to finish in order to highlight the offending string)?
- 我该如何执行此检查?
- 我怎样才能知道
list
找到了哪个字符串,如果可能的话(从头到尾以突出显示有问题的字符串)?
This would be useful for a blacklist.
这对黑名单很有用。
回答by SPKB24
Is this what you are looking for?
这是你想要的?
for item in list:
if item in st:
print item
break
else:
print "No string in list was matched"
回答by Eugene K
for x in list:
loc = st.find(x)
if (loc != -1):
print x
print loc
string.find(i) returns the index of where the substr i begins in st, or -1 on failure. This is the most intuitive answer in my opinion, you can make this probably into a 1 liner, but I'm not a big fan of those usually.
string.find(i) 返回 substr i 在 st 中开始的位置的索引,失败时返回 -1。在我看来,这是最直观的答案,你可以把它做成一个 1 线,但我通常不是那些的忠实粉丝。
This gives the extra value of knowing where the substring is found in the string.
这提供了知道子字符串在字符串中的位置的额外价值。
回答by ig-melnyk
You can do this by using list-comprehessions
您可以通过使用列表理解来做到这一点
ls = [item for item in lst if item in st]
UPD: You wanted also to know position :
UPD:您还想知道位置:
ls = [(item,st.find(item)) for item in lst if st.find(item)!=-1]
Result : [('admin', 4)
结果 : [('admin', 4)
You can find more information about List Comprehensions on this page
您可以在此页面上找到有关列表推导式的更多信息
回答by Amal G Jose
I am assuming the list is very large. So in this program, I am keeping the matched items in a list.
我假设这个列表非常大。所以在这个程序中,我将匹配的项目保存在一个列表中。
#declaring a list for storing the matched items
matched_items = []
#This loop will iterate over the list
for item in list:
#This will check for the substring match
if item in st:
matched_items.append(item)
#You can use this list for the further logic
#I am just printing here
print "===Matched items==="
for item in matched_items:
print item
回答by Hooting
list = ['admin', 'add', 'swear']
st = 'siteadmin'
if any([x in st for x in list]):print "found"
else: print "not found"
You can use any built-in function to check if any string in the list appeared in the target string
您可以使用任何内置函数来检查列表中的任何字符串是否出现在目标字符串中