Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading