Languages
[Edit]
EN

Python - custom string contains() method

0 points
Created by:
Dirask Community
6810

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

Python - string (popular problems)

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