Python String in String

white and black printer paper

To find if a Python string is in a string, use the in operator:

if "word" in somestring:
    # do something

To find the index at which the word occurs, use the find() method of a string:

somestring.find("word")

Examples

Let’s figure out if the word “This” occurs in a sentence:

sentence = "This is just a sentence"

if "This" in sentence:
    print("Found it!")

Output:

Found it!

Let’s then figure out the index at which it occurs:

sentence = "This is just a sentence"

idx = sentence.find("This")
print("The word 'This' begins at:", idx)

Output:

The word 'This' begins at: 0

An Edge Case

If you are using the in operator to figure out if a string is inside of another, check that the main string is not None. If you don’t, you get an error.

For example:

sentence = None

if "This" in sentence:
    print("Found it!")

Output:

TypeError: argument of type 'NoneType' is not iterable

To avoid this error, make sure to check against None like this:

sentence = None

if sentence is not None and "This" in sentence:
    print("Found it!")

Conclusion

Use in statement to check if a string is inside of another string in Python.

Use the string’s built-in find() method to figure out the index at which the string starts in another string.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *