[Tutor] Searching a text file's contents and comparing them toalist

Eric Hamiter ehamiter at gmail.com
Wed Jul 14 22:57:57 CEST 2010


Thanks for the pointers! This is now working, albeit probably ugly and clunky:


aisle_one = ["chips", "bread", "pretzels", "magazines"]
aisle_two = ["juice", "ice cream"]
aisle_three = ["asparagus"]

def find_groceries():
    with open("grocery_list.txt") as grocery_list:

        first_trip = ["Located on aisle 1: "]
        second_trip = ["Located on aisle 2: "]
        third_trip = ["Located on aisle 3: "]
        no_trip = ["Not found in the database: "]

        for item in grocery_list:
            item = item.rstrip()
            if item in aisle_one:
                first_trip.append(item)
            elif item in aisle_two:
                second_trip.append(item)
            elif item in aisle_three:
                third_trip.append(item)
            else:
                no_trip.append(item)

    sorted_list = first_trip, second_trip, third_trip, no_trip
    print sorted_list

find_groceries()


Last question (for today, at least): Right now, the output is less
than aesthetically pleasing:

(['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
found in the database: ', 'butter', 'soap'])

How can I format it so it looks more like this:

Located on aisle 1:
bread
magazines

Located on aisle 2
[etc...]


I tried putting "\n" into it but it just prints the literal string.
I'm sure it has to do with the list format of holding multiple items,
but so far haven't found a way to break them apart.

Thanks,

Eric


More information about the Tutor mailing list