Knowee
Questions
Features
Study Tools

Define the function count_substring(string, substring) that finds how many times the substring appears in the given string.Example:string = "Python is a powerful language. I want to learn Python"substring = "Python"Expected Output:2

Question

Define the function count_substring(string, substring) that finds how many times the substring appears in the given string.Example:string = "Python is a powerful language. I want to learn Python"substring = "Python"Expected Output:2

🧐 Not the exact question you are looking for?Go ask a question

Solution

To define the function count_substring, follow these steps:

  1. Start by defining the function count_substring with two parameters: string and substring.
  2. Initialize a variable called count and set it to 0. This variable will keep track of the number of times the substring appears in the string.
  3. Use the built-in method count() to count the number of occurrences of the substring in the string. Assign the result to the count variable.
  4. Return the value of the count variable as the output of the function.
  5. Here is the code implementation:
def count_substring(string, substring):
    count = string.count(substring)
    return count
  1. To test the function, you can use the provided example:
string = "Python is a powerful language. I want to learn Python"
substring = "Python"
print(count_substring(string, substring))

This will output: 2, as the substring "Python" appears twice in the given string.

This problem has been solved

Similar Questions

Write a python program to print the number of occurrences of a substring into a line

Write a Python program to count the number of occurrences of a specific character in a string

The function LEN() returns the total number of characters in a string

Write a python program to count the number of palindrome strings that occurred in the given string. Input:The input consists of a string.Output:count number of palindrome strings

In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.