count substring in text in python

To count a substring in a text in Python, you can use the built-in count() method of the string class.

Here's an example:

main.py
text = "This is an example text. Let's count the word 'example' in it."
subtring = "example"

count = text.count(subtring)

print(f"The word '{subtring}' appears {count} times in the text.")
191 chars
7 lines

Output:

main.py
The word 'example' appears 1 times in the text.
48 chars
2 lines

In this example, we define a string text and a substring substring. We call the count() method on the text string and pass it the substring as an argument. The method returns the number of occurrences of the substring in the text, which we store in the count variable.

We then print the result using an f-string, which allows us to include the value of count in the output.

related categories

gistlibby LogSnag