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.

To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.

About The Author

  • 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.

      • 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 😉

        • Shai

          Example is gone! …

          • Hmm, try this.

            # Our string to search, and the substring searches.
            s = 'Herp Derp'
            search_strs = ('Herp', 'Derp')
            # Case sensitive search.
            for search_str in search_strs:
            	if search_str in s:
            		print('Found {0}'.format(search_str))
            # Case insensitive search.
            s_lower = s.lower()
            for search_str in search_strs:
            	if search_str.lower() in s_lower:
            		print('Found {0}'.format(search_str))
  • 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!

  • Rich Tom

    There would be 200 plus of these strings. Can someone to help with Python Script?

    Given the strings in a XML file,

    <FORM easy_button="Y" gps_utc_time="$GPRMC,150231.000,…,115"

    I want to seek every string that has: gps_utc_time="$GPRMC, and look for the last few chars after ,115
    if after the , is less than 6 digits, change the string to …0
    if it is 6 digits numbers only without alphabet or #, then continue as write as its original string and output to new xml file

  • Crack’d Actor

    Very handy, cheers

  • which way is faster?