Python: search for string in list of tuples

Hello, I am trying to define a function that allows me to look up a string inside a list of tuples, then return the corresponding tuple. The search should NOT be case sensitive either…
Here is an example, as well as the defined function that I tried:

test_scores = [('math','89','92','75'),
              ('English','89','100'),
              ('science','87','95','91'),
              ('history','99','93','95')]

def searchScores(searchString):
    for i in range (len(test_scores)):
        for j in range (len(test_scores[i])):
            if test_scores[i][j].casefold()==searchString.casefold():
                print(test_scores[i])
                
searchScores('89')
print("---------------")
searchScores('History')
print("---------------")

^Thats not really the best example, but I just wanted to show how there may be a different number of items within each.

The output SHOULD look like this:

('math','89','92','75')
('English','89','100')
-----------------------
('history','99','93','95')

But sadly it only returned the “—” print statements.
Could someone give me guidance on how to fix this problem? I am not very experienced in this area so I am just having a hard time putting the pieces together. Thanks in advance :slight_smile: :grinning:

I’ve tried the code and it worked as expected.

Ah yes I have figured it out for the most part. See, the actual code I am using (it is very long, which is why I used an example), is formatted a bit differently, which I did not realize would affect it for some reason. It is more like (‘the first math grade is 89’, ‘the second math grade is 92’) and so on. Therefore it would not pick up the 89 because it was not by itself. Ended up switching some stuff and using the ‘in’ operator, however not sure how to stop it from printing duplicates :rofl:

There’s few ways to do that. One way or another it’s needed to keep which elements were already printed.

1 Like

figured it out :slight_smile: :

def searchScores(searchString):
    for t in test_scores:
        found = [searchString.lower() in c.lower() for c in t]
        if any (found):
            print(t)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.