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

Python- search through multiple arrays and print entire list if desired element is found

Here is my current code:

search=input('Enter a book title')

def read_book():
    booksdata=[]
    f=open('books2.txt', 'r')
    for record in f:
        cleanrecord=record.strip()
        books=cleanrecord.split(',')
        booksdata.append(books)
    f.close()
    return booksdata

read_book()

It opens up a text file that has data stored like this:

1, The Hunger Games, Adventure, Suzanne Collins, 1/08/2006, coai
2, Harry Potter and the Order of the Phoenix, Fantasy, J.K Rowling, 25/09/2021, ajyp

Im trying to program it so if the user types in ‘Hunger’, the entirety of the list(s) that contains hunger will get printed out:

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

['1', ' The Hunger Games', ' Adventure', ' Suzanne Collins', ' 1/08/2006', ' coai']

>Solution :

You need to check if your input is it in every row

search=input('Enter a book title')

def read_book():
    booksdata=[]
    f=open('books2.txt', 'r')
    for record in f:
        if search in record: # check
            cleanrecord=record.strip()
            books=cleanrecord.split(',')
            booksdata.append(books)
    f.close()
    return booksdata

result = read_book()
print (result) 

output:

 [['1', ' The Hunger Games', ' Adventure', ' Suzanne Collins', ' 1/08/2006', ' coai']]
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