Luke
Luke

Reputation: 760

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

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!

Upvotes: 4

Views: 278

Answers (2)

bgporter
bgporter

Reputation: 36494

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?

Upvotes: 11

Michel Keijzers
Michel Keijzers

Reputation: 15357

True in [i in 'abcdef' for i in 'afm']

gives True and

True in [i in 'nopqrst' for i in 'afm']

gives False

Upvotes: 0

Related Questions