I have a string, A = "abcdef"
, and several chars "a"
, "f"
and "m"
. I want a condition to make sure none of the chars appears in A
, i.e.,
if a not in A and f not in A and m not in A:
# do something
Is there a better way to do this? Thanks!
Sets are useful for this -- see the isdisjoint()
method:
Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.
new in version 2.6.
>>> a = "abcde"
>>> b = "ace"
>>> c = "xyz"
>>> set(a).isdisjoint(set(b))
False
>>> set(a).isdisjoint(set(c))
True
edit after comment
sets are still you friend. If I'm following you better now, you want this (or something close to it):
We'll just set everything up as sets to begin with for clarity:
>>> a = set('abcde')
>>> b = set('ace')
>>> c = set('acx')
If all of the chars in your set of characters is in the string, this happens:
>>> a.intersection(b) == b
True
If any of those characters are not present in your string, this happens:
>>> a.intersection(c) == c
False
Closer to what you need?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With