Checking Whether a String Contains a Set of Characters
Credit: Jürgen Hermann, Horst Hansen
Problem
You need to check for the occurrence of any of a set of characters in a string.
Solution
The solution generalizes to any sequence (not just a string), and any set
(any object in which membership can be tested with the
in operator, not just one of characters):
def containsAny(str, set):
""" Check whether sequence str contains ANY of the items in set. """
return 1 in [c in str for c in set]
def containsAll(str, set):
""" Check whether sequence str contains ALL of the items in set. """
return 0 not in [c in str for c in set]Discussion
While the
find and count string methods
can check for substring occurrences, there is no ready-made function
to check for the occurrence in a string of a set of characters.
While working on a condition to check whether a string contained the
special characters used in the glob.glob standard
library function, I came up with the above code (with help from the
OpenProjects IRC channel #python). Written this
way, it really is compatible with human thinking, even though you
might not come up with such code intuitively. That is often the case
with list comprehensions.
The following code creates a list of
1/0 values, one for each item
in the set:
[c in str for c in set]
Then this code checks whether there is at least one true value in that list:
1 in [c in str for c in set]
Similarly, this checks that no false values are in the list:
0 not in [c in str for c in set] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access