"
This article is part of in the series
Last Updated: Wednesday 29th December 2021

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:

[python]
>>> s = "It's not safe to go alone. Take this."
>>> 'safe' in s
True
>>> 'blah' in s
False
>>> if 'safe' in s:
... print('The message is safe.')
The message is safe.
[/python]

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:

[python]
>>> if s.find('safe') != -1:
... print('This message is safe.')
This message is safe.
[/python]

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.

About The Author