Check if substring is in a list of strings?

前端 未结 4 1810
灰色年华
灰色年华 2020-12-08 03:52

I have found some answers to this question before, but they seem to be obsolete for the current Python versions (or at least they don\'t work for me).

I want to chec

4条回答
  •  失恋的感觉
    2020-12-08 04:39

    You could use next instead:

    colors = ['yellow', 'orange', 'red'] 
    search = "or"
    
    result = next((True for color in colors if search in color), False)
    
    print(result) # True
    

    To show the string that contains the substring:

    colors = ['yellow', 'orange', 'red'] 
    search = "or"
    
    result = [color for color in colors if search in color]  
    
    print(result) # Orange
    

提交回复
热议问题