string="abcd123"
if "a" or "b" or "c" in string:
print("Yes")
is ther a shortcut for not typing "or" multiple times?
string="abcd123"
if "a" or "b" or "c" in string:
print("Yes")
is ther a shortcut for not typing "or" multiple times?
The shortcut (for the correctly written code if "a" in string or "b" in string or "c" in string:
) is the any
function and a generator expression:
if any(s in string for s in ("a", "b", "c")):
That will return True
as soon is it finds a value that is contained in string
, or False
if none are found; to search for more values, just add them to the inlined tuple
. If you need to know which value, you can use next
and a filtered genexpr to achieve a similar end result:
found_item = next((s for s in ("a", "b", "c") if s in string), None) # Returns first item found or None
if found_item is not None:
# Process found_item; it will be "a", "b" or "c", whichever was found first