Languages
[Edit]
EN

Python - custom string contains() method

0 points
Created by:
Teilsa
1255

In this article, we would like to show you how to check if the string contains a substring in Python.

Quick solution:

text = "ABC"
print("BC" in text)  # True

 

Practical example

In this example, we use in operator to create a custom implementation of the string contains() method and check if text contains some words.

text = "dirask is cool"

word_1 = "cool"
word_2 = "abc"


def contains(string, phrase):
    return phrase in string


print(contains(text, word_1))  # True
print(contains(text, word_2))  # False

Output:

True
False

Note:

You can also use string.find() method to find index of the specified substring.

text = "dirask is cool"
print(text.find("is"))  # 7

Alternative titles

  1. Python - string contains substring (custom implementation)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - string (popular problems)

Python - custom string contains() method
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join