Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if none of the multiple chars appears in string A?

Tags:

python

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!

like image 389
Luke Avatar asked Dec 21 '22 23:12

Luke


1 Answers

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?

like image 144
bgporter Avatar answered Dec 23 '22 13:12

bgporter