Count occurrences of a character in string in Python

PythonServer Side ProgrammingProgramming

We are given a string and a character. We want to find out how many times the given character is repeated in a given string.

With range and len

We design a for loop to match the character with every character present in the string which are accessed using index. The range and len function helps us determine how many times the matching has to be done when moving from left to right of the string.

Example

 Live Demo

Astr = "How do you do"
char = 'o'
# Given String and Character
print("Given String:\n", Astr)
print("Given Character:\n",char)
res = 0
for i in range(len(Astr)):
   # Checking character in string
   if (Astr[i] == char):
      res = res + 1
print("Number of time character is present in string:\n",res)

Output

Running the above code gives us the following result −

Given String:
How do you do
Given Character:
o
Number of time character is present in string:
4

With Counter

We apply the Counter function from the collections module to get the count of each character in the string. And then choose only those counts where the index matches with the value of the character we are searching for.

Example

 Live Demo

from collections import Counter
Astr = "How do you do"
char = 'o'
# Given String and Character
print("Given String:\n", Astr)
print("Given Character:\n",char)
count = Counter(Astr)
print("Number of time character is present in string:\n",count['o'])

Output

Running the above code gives us the following result −

Given String:
How do you do
Given Character:
o
Number of time character is present in string:
4
raja
Published on 04-Jun-2020 14:57:03
Advertisements