How to check if a python string contains a substring?
Tags: python, beginners, tutorial, programming
Published: 2021-05-26 11:43:15

In this python tutorial, we look at how you can check if a python string contains a substring. We look at the various methods and explain their use cases in detail.    

This tutorial is a part of our initiative at [Flexiple](https://flexiple.com/), to write short curated tutorials around often used or interesting concepts. However, in case you are here only for the solution use this link.   

### Table of Content

- [Why check if a python string contains a substring?](#why-check-if-a-python-string-contains-a-substring)
- [Using the in operator](#using-the-in-operator)
- [Using String Methods](#using-string-methods)
    - [index() method](#using-index)
    - [find() method](#using-find)
- [Limitations and Caveats](#limitations-and-caveats)

## Why check if a python string contains a substring?

We check if a python string contains a substring for multiple reasons, however, its most commonly used in conditional statements. This runs a code in case a substring exists and another if the python string does not contain the substring. Another common use is to find the index of the substring in the python string.

If you are coming from another language, it most likely that you have come across the `contains` function. Python also supports the `__contains__` method, however, it also supports a few faster and more readable methods to check if a python string contains a substring.

## Using the `in` operator:

The in operator is the most easiest and pythonic method to check if a python string contains a substring. The in and not in are membership operators, they take in two arguments and evaluate if one is a member of another. They return True in case it is a member and False in case it isn't. And hence it is used to check if a substring is a member of a python string. This is an efficient alternative to the **contains** method and can also be used to check if an item exists in a list.

The `in` is mainly used when the user only wants to check if it python string contains the substring and also because it is more readable. However, in case you are looking to return the index of the substring, the next solution is the goto.

### Syntax of `in`:

```python
'substring` in string
```

The syntax for `not in` is the same. 

### Code to check if python string contains a substring:

```python
if "Hire" in "Hire the top freelancers":
	print("Exists")
else:
	print("Dose not exist")

#Output - Exists
```

The `in` operator is case sensitive, and the above code would've returned a false if the substring was `"hire"` and hence is a good practice to use it with the `.lower()` method. This method converts the string to lower case. As strings are immutable, this would not affect the original string. 

```python
if "hire" in "Hire the top freelancers".lower():
	print("Exists")
else:
	print("Dose not exist")

#Output - Exists
```

## Using String Methods:

Python comes with a few string methods that can be used to check if a python string contains a substring. We look at the `find()` and `Index()` methods. These methods stand out from `in` as they return the index of the substring. However, they come with their cons we discuss them more in detail.

### Using `index()`

The `string.index()` method returns the starting index of the substring passed as a parameter. In this way, it could be used to check if a python string contains a substring. However, a major con is that in case the substring does not exist this method returns a `ValueError`  and hence it needs to be placed inside a `Try Except`.

**Syntax of `index()`:**

```python
string.index(value, start, stop)
```

Here `string` is the python string and `value` in the substring. The syntax also contains two optional parameters `start` and `stop` these are used in case you are looking for a substring within a particular index. 

**Code using `index()`:**

```python
try:
    "Hire the top freelancers".index("Hire")
except ValueError:
    print("Dose not exist")
else:
    print(sting.index(sti))

#Output = 0
```

Similar given `index()` is case sensitive and using the .lower() is recommended. 

```python
try:
    "Hire the top freelancers".lower().index("hire")
except ValueError:
    print("Dose not exist")
else:
    print(sting.index(sti))

#Output = 0
```

### Using `find()`

The `string.find()` is another method that can be used to check if the python string contains the substring. Similar to `index()` , `find()` also returns the starting index of the substring. But unlike the `index()` method it does not return a `ValueError` in case the substring does not exist but rather returns `-1` which is the index of the left-most string. 

**Syntax of `find()`:**  

```python
string.find(value, start, end)
```

The syntax and parameters of `find()`  are the same as `index()`

**Code using `find()`:**

```python
if "Hire the top freelancers".find("Hire") != -1:
    print("Hire the top freelancers".find("Hire"))
else:
    print("Dose not exist")
```

And again, since `find()` is also case sensitive the following code can be used.

```python
if "Hire the top freelancers".lower().find("hire") != -1:
    print("Hire the top freelancers".find("Hire"))
else:
    print("Dose not exist")
```

## Limitations and Caveats

- Remember to use the `.lower()` methods as all the methods are case sensitive.
- Which using the `index()` method to ensure it is placed inside an try and except condition.