1

I'm trying to make an address book for a school project, but I can't get my head around searching for values when part of the value is queried.

Here is the block of code at which I am stuck on:

self.ui.tableWidget.setRowCount(0)
with open("data.csv") as file:
    for rowdata in csv.reader(file):
        row = self.ui.tableWidget.rowCount()
        if query in rowdata:
            self.ui.tableWidget.insertRow(row)
            for column, data in enumerate(rowdata):
                item = QtGui.QTableWidgetItem(data)
                self.ui.tableWidget.setItem(row, column, item)

As you can see, I'm using a PyQt TableWidget to display search results from a csv file. The code above does work, but it only displays the result when a full query is given. The line of code that checks for a match is:

        if query in rowdata:

So for example, if I wanted to find someone called John, I would have to search for exactly "John". It wouldn't appear if I searched "Joh" or "john" or "hn" and so on...

If you require more information, just ask :P

1 Answer 1

1

What I think you want to do is search for query within the fields of your rows, not the whole row at once.

The problem you're having is that string in obj does different things depending on what type obj has. If it is a string, it does a substring search (like you want). If it is a non-string container however, it does a regular membership check (which is why it only finds exact matches now).

So to fix it, change your test from if query in rowdata to if any(query in field for field in rowdata). If you only want to search for matches within a specific field (like the contact's name) then it could be even simpler: if query in rowdata[name_column] (where name_column is the number of the column of the name field is in your CSV file).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Makes perfect sense, I guess. Thanks for providing a way of using specific columns as well! An upvote for you sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.