Does Python Have a String 'Contains' Substring Method?

Does Python Have a String 'Contains' Substring Method?

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

I want to do:

if not somestring.contains("blah"):
   continue
0

10 Answers

Use the in operator:

if "blah" not in somestring: 
    continue
15

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!")
else:
    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.

3

Does Python have a string contains substring method?

99% of use cases will be covered using the keyword, in, which returns True or False:

'substring' in any_string

For the use case of getting the index, use str.find (which returns -1 on failure, and has optional positional arguments):

start = 0
stop = len(any_string)
any_string.find('substring', start, stop)

or str.index (like find but raises ValueError on failure):

start = 100 
end = 1000
any_string.index('substring', start, end)
Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.