Ever wanted to see if a string contains a string in Python? Thought it was going to be complicated like C? Think again!

Python implements this feature in a very easy to read and easy to implement fashion. There are two ways of doing it, and some will like one way better than the other, so I'll leave it up to you to decide which one you like better.

The First Way: Using Python's in Keyword

The first way to check if a string contains another string is to use the in syntax. in takes two "arguments", one on the left and one on the right, and returns True if the left argument is contained within the right argument.

Here's an example:

You get the idea. That's all there is to it. The keyword in does all that magical work in the background for you, so there's no worrying about for loops or anything of that nature.

The Second Way: Using Python's str.find

This way is the less Pythonic way, but it's still accepted. It's longer and a little more confusing, but it still gets the job done.

This way requires us to call the find method on our string and check its return code.

Here's our example, using the string defined above:

Like I said above, this way is a little less clear, but it still gets the job done. The find method returns the position of the string within the string or -1 if it's not found. So we simply check if the position is not -1, and be on our merry way.

This article's length indicates just how easy it is to check for strings within strings in Python, and I hope it convinces you that the first way is far better than the second way, in terms of writing more Pythonic code.

Ta ta, for now.

  • MattB

    How would I do this if I wanted to search for multiple elements of the string?
    For example:

    s=str(“Herp Derp”)
    if “Herp” in s: print(“Found 1″)
    elif “Derp” in s: print(“Found 2″)
    elif “Herp” and “Derp” in s: print(“Found 1 and 2″)

    right now it still only prints “Found 1″. How do i get it to return a response only when multiple parts of the string are identified?

    • MattB

      I suppose there is a chunky way of doing this I figured out just now
      if “Herp” in s:
      if “Derp” in s:
      print(“Found 1 and 2″)

      however I hope to eventually implement this to look for about a dozen items within the string, an ever expanding loop seems clunky and not too practical.

      • http://jacksonc.com Jackson Cooper

        You don’t need to call the str() function, just quotes will do.

        Hmm, you could have a massive if statement with a bunch of ands. But I’d use a tuple. eg:

        Here’s an example: https://gist.github.com/jacks0n/7716671. I haven’t checked the code, but it should work ;)

  • asdf

    “Thought it was going to be complicated like C? ”

    It’s a lot easier than you think in C. Python’s “if x in y:” is “if (strstr(y, x))” – now, how that looks is another matter!

    • http://jacksonc.com Jackson Cooper

      Now try doing the same with an array of strings.