Here’s an example Python code to return the count of a given substring from a string:
# Define a function to count the number of occurrences of a substring in a string def count_substring(string, substring): count = 0 index = 0 while True: index = string.find(substring, index) if index == -1: break count += 1 index += len(substring) return count # Test the function with a sample string and substring string = "Hello, World! How are you today? World is beautiful." substring = "World" count = count_substring(string, substring) print("The count of substring '{}' in string '{}' is {}.".format(substring, string, count))
In this code, we define a function count_substring()
that takes two arguments: string
and substring
. This function uses the find()
method to search for the first occurrence of the substring
in the string
. If it finds a match, it increments the count
variable and continues searching for the next occurrence of the substring
starting from the index immediately after the last match. This process continues until the substring
is no longer found in the string
. Finally, the function returns the count
of the substring
.
In the main program, we test the count_substring()
function by calling it with a sample string
and substring
. We then use the print()
function to output the count of the substring
in the string
.
When you run this code, it should output:
The count of substring 'World' in string 'Hello, World! How are you today? World is beautiful.' is 2.
Note that you can replace the sample string
and substring
with any other values you want to test the function with.