【问题标题】:Searching for a title thats 'starts with' in python?在 python 中搜索“以”开头的标题?
【发布时间】:2016-08-19 15:53:11
【问题描述】:

所以我有一个名字列表

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)

【问题讨论】:

    标签: python


    【解决方案1】:

    将您的 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())
    

    【讨论】:

    • 为什么将它命名为search 会影响search 中的re.search?这就是命名空间的全部意义,这(根据禅宗)是一个很棒的主意(让我们做更多的事情!)...
    • 我收到了TypeError: argument of type 'bool' is not iterable
    • 发布完整的回溯@LiamEmery
    • 抱歉,我不知道如何让它看起来像 this
    • @mgilson,对不起大脑停止工作,我想我在想别的东西,删除了这个建议。利亚姆,matchStartWith = [movie for movie in movies_list if searchStr in movie.startswith(searchStr)] 应该是 matchStartWith = [movie for movie in movies_list if movie.startswith(searchStr)]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2021-03-11
    • 2022-11-01
    • 1970-01-01
    • 2013-07-13
    相关资源
    最近更新 更多