简体   繁体   中英

How to simplify an if statement checking common characters in a string?

I was wondering if there is a better way of expressing this if statement:

if any(i in word for i in '@/#')==False:

I am iterating through a list of strings and appending to a new list all of the strings that do not have the above characters (I also want to keep the old list). The above statement works but it is ugly and my IDE is telling me there might be a better way. Is there a way I can sort out the strings I want that is prettier or faster?

if not any(i in word for i in '@/#'):

or

if all(i not in word for i in '@/#'):

There's almost never a good reason to compare a boolean to True or False with == .

You could try like this:

characters = set('@/#')

and then:

if characters.isdisjoint(word):

or alternatively (but a bit slower, which may be meaningful for extremely long strings):

if not characters.intersection(word):

(with a better name instead of characters relating to its conceptual meaning of course)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM