简体   繁体   中英

How to use the for loop to find whether a person's name contains a string and print them out on Python?

I have just begun learning Python and I'm doing an assignment where I have to use the search_string to find within a tuple, anyone whose name contains the search_string and print them out and then tell the user how many matches there were out of the total number of people in the group. I have tried using a for loop, but didn't know how to configure it and ended up creating large, marginal errors. The code can be found below, but please don't give me direct answers! Just nudge me in the right direction because I do want to be able to solve this myself so that I can learn how to do things properly and learn from my own mistakes.

CODE:

names = [("Rachel B.", 1), ("George D.", 2), ("Crainer K.", 3), ("Baxter M.", 4), ("Marsh P.", 5), ("William R.", 6), ("Alexander S.", 7), ("Evan S.", 8), ("Archer U.", 9)]

amount = len(names)

The code below tells the number of people in the group.

print(amount)

The one below asks for the phrase or partial name.

search_string = str(input("Please enter a letter or partial name."))

This below is supposed to be where I have to find anyone whose name contains the search_string within the tuple and print them out whilst also telling how many matches there were out of the total number of people.

for search_string in names:
  if search_string in names:

You can try this.

count = 0

for name in names:
  if search_string in name:
    print(name)
    count += 1

print(count)
names = [("Rachel B.", 1), ("George D.", 2), ("Crainer K.", 3), ("Baxter M.", 
4), ("Marsh P.", 5), ("William R.", 6), ("Alexander S.", 7), ("Evan S.", 8), 
("Archer U.", 9)]

print("total number of name in the list is : " + str(len(names)))

search_string = input("enter the search_string: ")
name = [name[0] for name in names]
pos = [index[1] for index in names]

i=0

for x in name:
    if search_string in x:
        print(x)
        print(pos[i])
        print(names[i])
    i = i+1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM