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

后端 未结 1 1094
走了就别回头了
走了就别回头了 2021-01-28 05:15

So I have a list of names

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

I

相关标签:
1条回答
  • 2021-01-28 05:31

    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())
    
    0 讨论(0)
提交回复
热议问题