# Python Contains String: Check for Substring Matches

> Use the in operator to check if a Python string contains a substring, or call startswith(), endswith(), find(), and index() for position-specific matching

**URL:** https://sentry.io/answers/test-whether-a-string-contains-a-substring-in-python/

---

## The Problem

How can we test whether a string contains a given substring in Python? Do Python strings have a `contains()` method?

## The Solution

The pythonic way to determine whether a string contains a substring is by using the `in` operator:

```python
if "word" in "This string contains word.":
    print("Found 'word' in string!")
```

Under the hood, this operator will use the `str` class's  `__contains__()` method. Therefore, we could also write this code in the following way and get the same result:

```python
if "This string contains word.".__contains__("word"):
    print("Found 'word' in string!")
```

However, this is unpythonic, as methods starting with underscores are considered private. Calling them externally should be avoided where possible, even though Python does not prevent you from doing so.

This operation will return a boolean value, indicating whether the substring was found somewhere in the string. [`startswith()`](https://docs.python.org/3/library/stdtypes.html#str.startswith) and [`endswith()`](https://docs.python.org/3/library/stdtypes.html#str.endswith) can be used to test whether it was found at the beginning or end. To return the exact position of the substring, use [`find()`](https://docs.python.org/3/library/stdtypes.html#str.find) or [`index()`](https://docs.python.org/3/library/stdtypes.html#str.index).

---

*Source: [sentry.io/answers/test-whether-a-string-contains-a-substring-in-python/](https://sentry.io/answers/test-whether-a-string-contains-a-substring-in-python/)*
