how to search an element in a list using python?

Clem-Clem123 :

I created a function that would delete elements from a text file. I now want to make sure that the element the user wants to delete is actually in the file. However, now no matter if the element is actually in the list or not it always prints "Student was not found" and idk why... Could somoene explain to me?

This is my code:

def delete_a_record(filename):

    x=input("Remove Student's Name:")
    y=input("Remove Last Name:")

    with open(filename, "r") as f:
        lines = f.readlines()
        print(lines)
        if x not in lines and y not in lines:
            print("Student was not found")
        else:
            print("Student was deleted")
        with open(filename, "w") as f:
        for i in lines:
            t=i.split()
            if t[0]!=x and t[1]!=y:
                f.write(i)


    f.close()
    delete_a_record("mytextfile.txt")
wjandrea :

Here's an example list of strings and a string I want to find in it:

L = ['ab', 'cd', 'ef']
s = 'a'

If I want to find out if s is in a string in the list, I can't do s in L because 'a' isn't in the list, 'ab' is. What I can do though is loop over the list and check if s is in any element:

any(s in x for x in L)

Assuming the lines in your file are of the form FirstName LastName OtherInfo

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=375629&siteId=1