3

To check if a string contains a substring, one can use "in" like so:

if "abc" in str:
    print("yay")

And to check if a string contains one of two substrings one can use "or" like so:

if "abc" in str or "def" in str:
    print("yay")

My question is whether or not python has a way to simplify that into something like this:

if "abc" or "def" in str:
    print("yay")

I know this won't work as intended because it will always evaluate to true. (Python will check for at least one of the two statements, either

  • "abc"
  • "def" in str

being true and "abc" will always evaluate to true)

Having said that, is there anyway to check for such a condition other than this, rather verbose, method:

if "abc" in str or "def" in str:
    print("yay")
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
CSCH
  • 621
  • 6
  • 15

3 Answers3

4
if any(word in sentence for word in {"abc", "def"}):
    print("yay")
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
4

Put them in an array and do:

if any(x in word for x in a):

This has been answered here Check if multiple strings exist in another string

Community
  • 1
  • 1
Pavel
  • 1
  • 3
  • 17
  • 51
  • 2
    Do not use `str` as a variable name as it is a built-in – Bhargav Rao Jun 25 '15 at 19:35
  • I wasn't sure exactly how to word my google searches when I came across this issue. I didn't know it was already asked. Thanks -- I have flagged the question for deletion as I can no longer do it myself. – CSCH Jun 25 '15 at 19:37
  • @BhargavRao built in as what? It doesn't matter, this will still compile and work – Pavel Jun 25 '15 at 19:38
  • 2
    [`str`](https://docs.python.org/2/library/functions.html#str) in Python has a reserved builtin function. Using that as a variable name will hinder the ability of you using that function. So henceforth please do not use that as a variable name – Bhargav Rao Jun 25 '15 at 19:40
  • 1
    It would compile and work, but then good luck trying to cast objects as strings with `str(my_object)`. – TigerhawkT3 Jun 25 '15 at 19:43
  • For this example it works is all im saying – Pavel Jun 25 '15 at 19:43
  • 2
    @paulpaul1076 doesn't matter, still a bad practice – vaultah Jun 25 '15 at 19:44
  • @paulpaul1076 Thanks that was all that was needed. I have reversed my downvote to upvote. Remember this in future. – Bhargav Rao Jun 25 '15 at 19:44
  • "For this example it works" is no justification for code that's liable to blow up in the developer's face. – TigerhawkT3 Jun 25 '15 at 19:49
2

If your question is like whether there is a way, to check whether any string in given list of strings exist in a bigger string . We can use the any() function along with generator expressions for that.

Example -

>>> s = "Hello World Bye Abcd"
>>> l = ["Hello","Blah"]
>>> l1 = ["Yes","No"]
>>> any(li in s for li in l)
True
>>> any(li in s for li in l1)
False
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176