简体   繁体   中英

Searching for a title thats 'starts with' in python?

So I have a list of names

name_list = ["John Smith", "John Wrinkle", "John Wayne", "David John", "David Wrinkle", "David Wayne"]

I want to be able to search, for example, John and

John Smith
John Wrinkle
John Wayne

will display. At the moment my code will display

John Smith
John Wrinkle
John Wayne
David John

What am I doing wrong?

Here is my code

search = input(str("Search: "))
search = search.lower()
matches = [name for name in name_list if search in name]
for i in matches:
    if(search == ""):
        print("Empty search field")
        break
    else:
        i = i.title()
        print(i)

Change your matches to:

matches = [name for name in name_list if name.startswith(search)]

You can also make some changes to your code:

# You can do this in one go
search = input(str("Search: ")).lower()

# Why bother looping if search string wasn't provided.
if not search:
    print("Empty search field")
else:
             # This can be a generator
    for i in (name for name in name_list if name.startswith(search)):
        print(i.title())

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