Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I check that a string does not contain any string from a list?

For example, where:

list = [admin, add, swear]
st = 'siteadmin'

st contains string admin from 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)?

This would be useful for a blacklist.

like image 756
StringsOnFire Avatar asked Aug 20 '15 14:08

StringsOnFire


People also ask

How do you check if a string contains an element from a list in Python?

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.

How do you check if a string contains another string in Python?

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.

How do you check if a value exists in a list in Python?

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.


3 Answers

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

like image 184
Hooting Avatar answered Sep 22 '22 08:09

Hooting


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

like image 36
ig-melnyk Avatar answered Sep 25 '22 08:09

ig-melnyk


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
like image 28
Amal G Jose Avatar answered Sep 22 '22 08:09

Amal G Jose