KRZ
KRZ

Reputation: 3

How to check if an input string is part of any component of any tuple

I am having issues with using an input string and checking to see if it is part of a tuple in the data list.

data = [(Mr. John Doe, 345.678.9765, [email protected]),
        (Ms. Mary Doe, 345.123.4567, [email protected])]
print("Search for: ")
s = input()
while s:
   for a in data:
    if any(b[0] == s for b in a):
        print(a)
    else:
        print("Not Found")
print("Search for: ")
s = input() 

If I enter in Mr. as the input it will fail to find the component in the tuple, but if I enter j as the input it will print out:

 (Mr. John Doe, 345.678.9765, [email protected]) 

Upvotes: 0

Views: 49

Answers (1)

any(b[0] == s for b in a) will only be True if the user inputs the full name exactly as it is in name string, (e.g. Mr. John Doe). Instead, check if the user input is in any part of the name string using the in operator:

data = [('Mr. John Doe', '345.678.9765', '[email protected]'),
        ('Ms. Mary Doe', '345.123.4567', '[email protected]')]

print("Search for: ")

s = input()

result = None # set a variable to hold our result

for a in data:
    if any(s in b for b in a): # use in to check if substring 's' is in string 'b'
        result = a[0]  # save the name that contains user input
        break          # exit loop if found
    else:
        result = "Not Found"

print(result)

The reason it was failing with Mr. input is because b[0] in b[0] == s for b in a refers to the first letter in each string in the tuple, and a 3-character string will never equal a single character.

Similarly, when we input j, the comparison b[0] == s for b in a does match the first character in the last string of the first tuple (j in [email protected]), so it did output that tuple.

Hope this helps.

Upvotes: 1

Related Questions