Track the occurrences of a character in a string in Python

In Python, A string is a collection of characters enclosed in single (‘ ‘) or double (” “) quotes. This article is written to emphasize the Number of occurrences of a character in a string in Python.

Method1: Number of occurrences of a character in a string in Python


Usually to track the number of occurrences of a character in python, one can use the method count. The syntax for count ob a substring in string ‘str’ is:

>>Str.count(substring(start,end))

Here, the substring is a compulsory parameter which is to be entered for the method to yield the desired results. For example: the string str = “Happy Birthday” , for counting the number of occurences of character a in the string can be counted using:

>>str.count(‘a’)

The parameters start and end are optional to enter parameters. One can enter the  starting and ending index of the string where the string starts and ends respectively.

The output would be : 2

This would be the in-built method in Python to track the number of occurences of character in a string.

Method2 : occurrences of a character in a string in Python

 


The other way to solve this problem is the following code:

def Counting():
        Stry=input("Enter the string you want to operate on")
        sub_str=input("Enter the substring you want to count")
        counter=0
        for i in list(Stry):
               if i==sub_str:
                    counter=counter+1
        print(counter)

We are using a user-defined function ‘Counting’ to track the occurrences of a character in a string.

  • Variable ‘Stry’ is used to enter the string on which the counting of character occurrence is supposed to take place.
  • Variable ‘sub_str’ is used to enter the substring or character whose occurrences are to be counted.
  • The variable’counter’ is assigned to integer 0.
  • A for loop is used to traverse the list created after typecasting the string to a list. As a result, each character in the string can be traversed and accessed.
  • Using an if condition, whenever the substring or character makes an appearance, the counter is incremented by 1.
  • Then the variable counter is printed.

 

Note: The second program can only be used for a substring of a single character. That is what makes it different from the count method. In the count method, one can track the occurrences of a substring ( a collection of characters present in the string) as well.

For eg:

st="Code Academy"

st.count('de')

Output: 2

 

Leave a Reply

Your email address will not be published. Required fields are marked *