简体   繁体   English

在python中搜索“开头为”的标题?

[英]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

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更改为:

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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