How to search for value in a sequence in Python?

3985 views python

I am very new to coding so please bear with me. Basically I am writing a program that will ask for either a last name or id number, then search a .csv file for the word and return the entire column to which it belongs. Below is what I have written if the user opts to search by the id.

method = input("Search by invoice id (id) or customer last name (lname)?: ")
    data = "data.csv"
    dataFile = open(data, "r")
    dataRows = dataFile.readlines()

if method == "id":
    term = input("Enter the id: ")
    for line in dataRows:
        row = line.strip()
        newRow = row.split('\n')
        if term == newRow[0]:
            print("No matches found.")

This is the csv file: Here is a photo of the csv file.

This is how it prints out after readlines():

['invoice id,first name,last name,part number,quantity,total']

Since invoice ID is the first column, I thought it would be found by using if term ==newRow[0], but that's not working. Any tips? Thanks so much.

answered question

you should use the csv module when handling CSVs. all of the row splitting and other operations are taken care of for you

@RoadRunner i added it, thank you!

If the data is comma separated, shouldn't it be: newRow = row.split(',')?

@aydow unfortunately our teacher hasn't taught us that, but good idea!

1 Answer


If you don't want to use the csv module for this problem, then you should split your string on ",", not on "\n":

newRow = row.split(",")

This way, the first element of newRow will be the invoice id.

posted this

Have an answer?


Please login first before posting an answer.