Python check if string contains another string with example

String manipulation is a common task in any programming language. Python provides two common ways to check if a string contains another string.

Python check if string contains another string

Python string supports in operator. So we can use it to check if a string is part of another string or not. The in operator syntax is:

It returns True if “sub” string is part of “str”, otherwise it returns False.

Let’s look at some examples of using in operator in Python.

Output:

If you are not familiar with f-prefixed strings in Python, it’s a new way for string formatting introduced in Python 3.6. You can read more about it at f-strings in Python.

When we use in operator, internally it calls __contains__() function. We can use this function directly too, however it’s recommended to use in operator for readability purposes.

Output:

Using find() to check if a string contains another substring

We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.

Output:

You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply