在python中搜索'以'开头'的标题?

时间:2016-04-26 02:47:03

标签: python

所以我有一个名单

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

我希望能够搜索,例如John

John Smith
John Wrinkle
John Wayne

将显示。目前我的代码将显示

John Smith
John Wrinkle
John Wayne
David John

我做错了什么?

这是我的代码

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)

1 个答案:

答案 0 :(得分:6)

将您的matches更改为:

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

您还可以对代码进行一些更改:

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