Search code examples
pythonfor-loopsearchconcatenationlogical-operators

How can I join multiple strings with logical operators to create a search term with for loop in python


I want to create a search term, depending on the input given. For example, when the user provides the phone number "69420" and name "Karen", the following code:

getbools = [f"{phone}" != "", f"{id}" != "", f"{name.replace(' ', ':')}" != "", f"{email}" != ""] #  [1, 0, 1, 0]
searches = [f"{phone}", f"{id}", f"{name.replace(' ', ':')}", f"{email}"]
search = operator.and_.join(search for i in searches if getbools[i])
print(search)

should yield a the following search term

search = "69420" and "Karen"

However, I get the following error:

AttributeError: 'builtin_function_or_method' object has no attribute 'join'

I want to use this search term afterwards in a for loop searching the search in the lines of a .txt file and further process them. Sadly, I could not come up with a solution yet and probably, I'm overcomplicating this and there's a simpler way. Hope you can help me find a better solution.

Thanks in advance!


Solution

  • # Open the txt files using the context manager `with` statement
    with open("txtfile.txt") as f:
        txtfile = f.readlines()
    
    # Get the search terms
    searches = [f"{phone}", f"{id}", f"{name.replace(' ', ':')}", f"{email}"]
    # Removes falsy values (like you did with `!= ""`)
    searches = [element for element in searches if element]
    
    # Loop thru the lines and check if all search terms occur. 
    # If they do, print the line
    for line in txtfile:
        if all(search_term in line for search_term in searches):
            print(line.strip())
    

    As a side note, its better practise to call your id variable id_ or something, so it doesn't overwrite the built-in id function.