1
string="abcd123"
if "a" or "b" or "c" in string:
    print("Yes")

is ther a shortcut for not typing "or" multiple times?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

2

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
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Note: If the set of things to search for ("needles") is *huge*, and you need to know all of the ones found in the haystack, you might want to look at [my old answer on optimizing this scenario with Aho-Corasick](https://stackoverflow.com/a/34820772/364696). Not worth it for just three strings to check normally (*maybe* if `string` was multiple GBs in size...), but worth noting when performance counts and you're testing for a lot of substrings. – ShadowRanger Mar 31 '22 at 03:29