Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a string to multiple items in Python [duplicate]

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, daemon, cron, ftp, lpr, kern, mail, news, syslog, user, uucp, local0, ... , local7

Is there an efficient way of doing this other than:

if facility == "auth" or facility == "authpriv" ...

1 Answers

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.

like image 160
pillmuncher Avatar answered Sep 05 '25 16:09

pillmuncher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!