число вхождений в него некоторого буквосочетания. in python

To count the number of occurrences of a particular substring within a given string in Python, you can use the count method of the string. Here's an example:

main.py
string = "Hello, this is a sample string. It contains multiple occurrences of the word sample."
substring = "sample"

count = string.count(substring)
print(f"The substring '{substring}' occurs {count} times in the string.")
224 chars
6 lines

This will output:

main.py
The substring 'sample' occurs 2 times in the string.
53 chars
2 lines

In the example above, the count method is used on the string object with the substring as an argument. It returns the number of occurrences of the substring within the string, and we store that count in the count variable. Finally, we print out the result using an f-string.

related categories

gistlibby LogSnag