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.py191 chars7 lines
Output:
main.py48 chars2 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.
gistlibby LogSnag