Comparing a string to multiple items in Python

后端 未结 3 1751
后悔当初
后悔当初 2020-11-22 15:23

I\'m trying to compare a string called facility to multiple possible strings to test if it is valid. The valid strings are:

auth, authpriv, daem         


        
相关标签:
3条回答
  • 2020-11-22 15:56

    Unless your list of strings gets hideously long, something like this is probably best:

    accepted_strings = ['auth', 'authpriv', 'daemon'] # etc etc 
    
    if facility in accepted_strings:
        do_stuff()
    
    0 讨论(0)
  • 2020-11-22 16:08

    To efficiently check if a string matches one of many, use this:

    allowed = set(('a', 'b', 'c'))
    if foo in allowed:
        bar()
    

    set()s are hashed, unordered collections of items optimized for determining whether a given item is in them.

    0 讨论(0)
  • 2020-11-22 16:22

    If, OTOH, your list of strings is indeed hideously long, use a set:

    accepted_strings = {'auth', 'authpriv', 'daemon'}
    
    if facility in accepted_strings:
        do_stuff()
    

    Testing for containment in a set is O(1) on average.

    0 讨论(0)
提交回复
热议问题