How to make it shorter (Pythonic)?

前端 未结 6 826
半阙折子戏
半阙折子戏 2021-02-15 16:56

I have to check a lot of worlds if they are in string... code looks like:

if \"string_1\" in var_string or \"string_2\" in var_string or \"string_3\" in var_stri         


        
6条回答
  •  清歌不尽
    2021-02-15 17:26

    This is one way:

    words = ['string_1', 'string_2', ...]
    
    if any(word in var_string for word in words):
        do_something()
    

    Reference: any()

    Update:

    For completeness, if you want to execute the function only if all words are contained in the string, you can use all() instead of any().

    Also note that this construct won't do any unnecessary computations as any will return if it encounters a true value and a generator expression is used to create the Boolean values. So you also have some kind of short-circuit evaluation that is normally used when evaluating Boolean expressions.

提交回复
热议问题