For example, where:
list = [admin, add, swear]
st = 'siteadmin'
st
contains string admin
from list
.
list
was found, and if possible where (from start to finish in order to highlight the offending string)?This would be useful for a blacklist.
Use the any() function to check if a string contains an element from a list, e.g. if any(substring in my_str for substring in my_list): . The any() function will return True if the string contains at least one element from the list and False otherwise.
Using find() to check if a string contains another substring We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.
We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.
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
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 :
ls = [(item,st.find(item)) for item in lst if st.find(item)!=-1]
Result : [('admin', 4)
You can find more information about List Comprehensions on this page
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With