Does Python have a string 'contains' substring method?

Blankman Source

I'm looking for a string.contains or string.indexof method in Python.

I want to do:

if not somestring.contains("blah"):


answered 8 years ago eldarerathis #1

If it's just a substring search you can use string.find("substring").

You do have to be a little careful with find, index, and in though, as they are substring searches. In other words, this:

s = "This be a string"
if s.find("is") == -1:
    print "No 'is' here!"
    print "Found 'is' in the string."

It would print Found 'is' in the string. Similarly, if "is" in s: would evaluate to True. This may or may not be what you want.

answered 8 years ago Michael Mrozek #2

You can use the in operator:

if "blah" not in somestring: 

answered 8 years ago Alex Martelli #3

if needle in haystack: is the normal use, as @Michael says -- it relies on the in operator, more readable and faster than a method call.

If you truly need a method instead of an operator (e.g. to do some weird key= for a very peculiar sort...?), that would be 'haystack'.__contains__. But since your example is for use in an if, I guess you don't really mean what you say;-). It's not good form (nor readable, nor efficient) to use special methods directly -- they're meant to be used, instead, through the operators and builtins that delegate to them.

answered 7 years ago Harish Reddy #4

Another way to find whether a string contains a few characters or not with the Boolean return value (i.e. True or `False):

str1 = "This be a string"
find_this = "tr"
if find_this in str1:
    print find_this, " is been found in ", str1
    print find_this, " is not found in ", str1

answered 5 years ago Bohdan #5

No, there isn't any string.contains(str) method, but there is the in operator:

if substring in someString:
    print "It's there!!!"

Here is a more complex working example:

# Print all files with dot in home directory
import commands
(st, output) = commands.getstatusoutput('ls -a ~')
print [f for f in output.split('\n') if '.' in f ]

answered 4 years ago Aaron Hall #6

Does Python have a string contains substring method?

Yes, but Python has a comparison operator that you should use instead, because the language intends its usage, and other programmers will expect you to use it. That keyword is in, which is used as a comparison operator:

>>> 'foo' in '**foo**'

The opposite (complement), which the original question asks for, is not in:

>>> 'foo' not in '**foo**' # returns False

This is semantically the same as not 'foo' in '**foo**' but it's much more readable and explicitly provided for in the language as a readability improvement.

Avoid using __contains__, find, and index

As promised, here's the contains method:

str.__contains__('**foo**', 'foo')

returns True. You could also call this function from the instance of the superstring:


But don't. Methods that start with underscores are considered semantically private. The only reason to use this is when extending the in and not in functionality (e.g. if subclassing str):

class NoisyString(str):
    def __contains__(self, other):
        print('testing if "{0}" in "{1}"'.format(other, self))
        return super(NoisyString, self).__contains__(other)

ns = NoisyString('a string with a substring inside')

and now:

>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"

Also, avoid the following string methods:

>>> '**foo**'.index('foo')
>>> '**foo**'.find('foo')

>>> '**oo**'.find('foo')
>>> '**oo**'.index('foo')

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
ValueError: substring not found

Other languages may have no methods to directly test for substrings, and so you would have to use these types of methods, but with Python, it is much more efficient to use the in comparison operator.

Performance comparisons

We can compare various ways of accomplishing the same goal.

import timeit

def in_(s, other):
    return other in s

def contains(s, other):
    return s.__contains__(other)

def find(s, other):
    return s.find(other) != -1

def index(s, other):
    except ValueError:
        return False
        return True

perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),

And now we see that using in is much faster than the others. Less time to do an equivalent operation is better:

>>> perf_dict
{'in:True': 0.16450627865128808,
 'in:False': 0.1609668098178645,
 '__contains__:True': 0.24355481654697542,
 '__contains__:False': 0.24382793854783813,
 'find:True': 0.3067379407923454,
 'find:False': 0.29860888058124146,
 'index:True': 0.29647137792585454,
 'index:False': 0.5502287584545229}

answered 3 years ago ytpillai #7

Here is your answer:

if "insert_char_or_string_here" in "insert_string_to_search_here":

For checking if it is false:

if not "insert_char_or_string_here" in "insert_string_to_search_here":


if "insert_char_or_string_here" not in "insert_string_to_search_here":

answered 3 years ago Rahul Gupta #8

Basically, you want to find a substring in a string in python. There are two ways to search for a substring in a string in Python.

Method 1: in operator

You can use the Python's in operator to check for a substring. It's quite simple and intuitive. It will return True if the substring was found in the string else False.

>>> "King" in "King's landing"

>>> "Jon Snow" in "King's landing"

Method 2: str.find() method

The second method is to use the str.find() method. Here, we call the .find() method on the string in which substring is to found. We pass the substring to the find() method and check its return value. If its value is other than -1, the substring was found in the string, otherwise not. The value returned is the index where substring was found.

>>> some_string = "valar morghulis"

>>> some_string.find("morghulis")

>>> some_string.find("dohaeris")

I would recommend you to use the first method as it is more Pythonic and intuitive.

answered 3 years ago Ufos #9

So apparently there is nothing similar for vector-wise comparison. An obvious Python way to do so would be:

names = ['bob', 'john', 'mike']
any(st in 'bob and john' for st in names) 
>> True

any(st in 'mary and jane' for st in names) 
>> False

answered 2 years ago Inconnu #10

In Python there are two simple ways you can achieve this:

The Pythonic way: Using Python's 'in' Keyword-

in takes two "arguments", one on the left(substring) and one on the right, and returns True if the left argument is contained within the rightside argument and if not,it returns False.

example_string = "This is an example string"
substring = "example"
print(substring in example_string)



The non-Pythonic way: Using Python's str.find:

The find method returns the position of the string within the string or -1 if it's not found. But simply check if the position is not -1.

if example_string.find(substring) != -1:
    print('Substring found!')
    print('Substring not found!')


Substring found!

answered 1 year ago firelynx #11

in Python strings and lists

Here are a few useful examples that speak for themselves concerning the in method:

"foo" in "foobar"

"foo" in "Foobar"

"foo" in "Foobar".lower()

"foo".capitalize() in "Foobar"

"foo" in ["bar", "foo", "foobar"]

"foo" in ["fo", "o", "foobar"]

Caveat. Lists are iterables, and the in method acts on iterables, not just strings.

answered 6 months ago Jamie Bull #12

If you're looking for case-insensitive search for whole words, rather than a substring contained within another word:

s = 'This is my text example'
if 'is' not in (w.lower() for w in s.split(string.punctuation + string.whitespace)):
     # do something

answered 4 months ago Jeffrey04 #13

If you are happy with "blah" in somestring but want it to be a function call, you can probably do this

import operator

if not operator.contains(somestring, "blah"):

All operators in Python can be more or less found in the operator module including in.

answered 1 month ago Fipsi #14

I see there are already answers but I want to add my two cents as well.

In Python there are functions to do this but the most simple (and mostly preferred) method is to use the keyword in :

"test" in "testtext"

"abc" in "abcdefg"

"abc" in "Abc"

"ABC" in "abc"

"abc" in "def"

"abc" in ["abc", "def", "ghi"]

There are some string methods as well:

2 #returns the index of the first match

-1 #returns -1 if the substring 
#could not be found in the string

# and:


ValueError: substring not found
#raises ValueError...

About performance:

In general in is the fasted method to find a substring...

find is slightly faster than index

Hope I could help!

comments powered by Disqus