In this article we will discuss different ways to count occurrences of a single character or some selected characters in a string and find their index positions in the string.


Count Occurrences of a single character in a String using string.count()

In Python the String class contains a method to count to the occurrences of a character or string in the string object i.e.

string.count(s, sub[, start[, end]])

It looks for the character or string s in range start to end and returns it’s occurrence count. If start & end is not provided then it will look in complete string and return the occurrence count of s ( character or string) in the main string. Let’s use string.count() to count the occurrences of character ‘s’ in a big string i.e.
mainStr = 'This is a sample string and a sample code. It is very Short.'

# string.count() returns the occurrence count of given character in the string
frequency = mainStr.count('s')

print("Occurrence Count of character 's' : " , frequency)

Output:
Occurrence Count of character 's' :  6

Count Occurrences of a single character in a String using collections.Counter()

collections.counter(iterable-or-mapping)

Counter is a dict subclass and collections.Counter() accepts an iterable entity as argument and keeps the elements in it as keys and their frequency as value. So, if we pass a string in collections.Counter() then it will return a Counter class object which internally has characters as keys and their frequency in string as values. Let’s use that to find the occurrence count of character ‘s’ in a string i.e.
mainStr = 'This is a sample string and a sample code. It is very Short.'

# Counter is a dict sub class that keeps the characters in string as keys and their frequency as value
frequency = Counter(mainStr)['s']

print("Occurrence Count of character 's' : ", frequency)

Output:
Occurrence Count of character 's' :  6

Counter() returned a Counter class ( sub-class of dict) object containing all characters in string as key and their occurrence count as value. We fetched the occurrence count of character ‘s’ from it using [] operator.

Python Regex : Count occurrences of a single character using regex

We can also find the frequency of a character in string using python regex i.e.

# Create a regex pattern to match character 's'
regexPattern = re.compile('s')

# Get a list of characters that matches the regex pattern
listOfmatches = regexPattern.findall(mainStr)

print("Occurrence Count of character 's' : ", len(listOfmatches))

Output:
Occurrence Count of character 's' :  6

We created a regex pattern to match the character ‘s’ and the find all occurrences of character that matched our pattern i.e. all occurrences of character ‘s’ as list. It’s length gives us the occurrence count of character ‘s’ in string.

Using python regex for this is kind of over kill but it is really useful if we are looking to count the occurrences of multiple characters in a string.

Count occurrences of multiple characters in string using Python regex

We will create a regex pattern to match the either character ‘s’ or ‘c’ and the find all occurrences of characters that matched our pattern i.e. all occurrences of either character ‘s’ & ‘c’ as list. It’s length gives us the occurrence count of both the characters in the string. For example,

mainStr = 'This is a sample string and a sample code. It is very Short.'

# Create a regex pattern to match either character 's' or 'c'
regexPattern = re.compile('[sc]')

# Find all characters in a string that maches the given pattern
listOfmatches = regexPattern.findall(mainStr)
print('List of mached characters : ', listOfmatches)
print("Total Occurrence Count of character 's' & 'c' : ", len(listOfmatches))
print("Occurrence Count of character 's' : ", listOfmatches.count('s'))
print("Occurrence Count of character 'c' : ", listOfmatches.count('c'))

Output:
List of mached characters :  ['s', 's', 's', 's', 's', 'c', 's']
Total Occurrence Count of character 's' & 'c' :  7
Occurrence Count of character 's' :  6
Occurrence Count of character 'c' :  1

Finding index positions of single or multiple characters in a string

Count Occurrences and find all index position of a single character in a String

To find the index positions of a given character in string using regex, create a regex pattern to match the character. Then iterate over all the matches of that pattern in the string and add their index positions to a list i.e.

mainStr = 'This is a sample string and a sample code. It is very Short.'

# Create a regex pattern to match character 's'
regexPattern = re.compile('s')

# Iterate over all the matches of regex pattern
iteratorOfMatchObs = regexPattern.finditer(mainStr)
indexPositions = []
count = 0
for matchObj in iteratorOfMatchObs:
    indexPositions.append(matchObj.start())
    count = count + 1

print("Occurrence Count of character 's' : ", count)
print("Index Positions of 's' are : ", indexPositions)

Output
Occurrence Count of character 's' :  6
Index Positions of 's' are :  [3, 6, 10, 17, 30, 47]

Find Occurrence count and index position of a multiple character in a String

Similarly we can find the index positions of multiple characters in the string i.e.

mainStr = 'This is a sample string and a sample code. It is very Short.'

# Create a regex pattern to match character 's' or 'a' or 'c'
regexPattern = re.compile('[sac]')

# Iterate over all the matches of regex pattern
iteratorOfMatchObs = regexPattern.finditer(mainStr)
count = 0
indexPositions = {}
for matchObj in iteratorOfMatchObs:
    indexPositions[matchObj.group()] = indexPositions.get(matchObj.group(), []) + [matchObj.start()]
    count = count + 1

print("Total Occurrence Count of characters 's' , 'a' and 'c' are : ", count)
for (key, value) in indexPositions.items():
    print('Index Positions of ', key , ' are : ', indexPositions[key])

Output:
Total Occurrence Count of characters 's' , 'a' and 'c' are :  12
Index Positions of  s  are :  [3, 6, 10, 17, 30, 47]
Index Positions of  a  are :  [8, 11, 24, 28, 31]
Index Positions of  c  are :  [37]

Complete example is as follows,
from collections import Counter
import re

def main():

   print('**** Count Occurrences of a single character in a String using string.count() **** ')
   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # string.count() returns the occurrence count of given character in the string
   frequency = mainStr.count('s')

   print("Occurrence Count of character 's' : " , frequency)

   print('**** Count Occurrences of a single character in a String using collections.Counter() **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Counter is a dict sub class that keeps the characters in string as keys and their frequency as value
   frequency = Counter(mainStr)['s']

   print("Occurrence Count of character 's' : ", frequency)

   print('**** Count Occurrences of a single character in a String using Regex **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Create a regex pattern to match character 's'
   regexPattern = re.compile('s')

   # Get a list of characters that matches the regex pattern
   listOfmatches = regexPattern.findall(mainStr)

   print("Occurrence Count of character 's' : ", len(listOfmatches))

   print('**** Count Occurrences of multiple characters in a String using Regex **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Create a regex pattern to match either character 's' or 'c'
   regexPattern = re.compile('[sc]')

   # Find all characters in a string that maches the given pattern
   listOfmatches = regexPattern.findall(mainStr)
   print('List of mached characters : ', listOfmatches)
   print("Total Occurrence Count of character 's' & 'c' : ", len(listOfmatches))
   print("Occurrence Count of character 's' : ", listOfmatches.count('s'))
   print("Occurrence Count of character 'c' : ", listOfmatches.count('c'))

   print('**** Count Occurrences and find all index position of a single character in a String **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Create a regex pattern to match character 's'
   regexPattern = re.compile('s')

   # Iterate over all the matches of regex pattern
   iteratorOfMatchObs = regexPattern.finditer(mainStr)
   indexPositions = []
   count = 0
   for matchObj in iteratorOfMatchObs:
       indexPositions.append(matchObj.start())
       count = count + 1

   print("Occurrence Count of character 's' : ", count)
   print("Index Positions of 's' are : ", indexPositions)

   print('**** Find Occurrence count and index position of a multiple character in a String **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Create a regex pattern to match character 's' or 'a' or 'c'
   regexPattern = re.compile('[sac]')

   # Iterate over all the matches of regex pattern
   iteratorOfMatchObs = regexPattern.finditer(mainStr)
   count = 0
   indexPositions = {}
   for matchObj in iteratorOfMatchObs:
       indexPositions[matchObj.group()] = indexPositions.get(matchObj.group(), []) + [matchObj.start()]
       count = count + 1

   print("Total Occurrence Count of characters 's' , 'a' and 'c' are : ", count)
   for (key, value) in indexPositions.items():
       print('Index Positions of ', key , ' are : ', indexPositions[key])



if __name__ == '__main__':
  main()

Output:
**** Count Occurrences of a single character in a String using string.count() **** 
Occurrence Count of character 's' :  6
**** Count Occurrences of a single character in a String using collections.Counter() **** 
Occurrence Count of character 's' :  6
**** Count Occurrences of a single character in a String using Regex **** 
Occurrence Count of character 's' :  6
**** Count Occurrences of multiple characters in a String using Regex **** 
List of mached characters :  ['s', 's', 's', 's', 's', 'c', 's']
Total Occurrence Count of character 's' & 'c' :  7
Occurrence Count of character 's' :  6
Occurrence Count of character 'c' :  1
**** Count Occurrences and find all index position of a single character in a String **** 
Occurrence Count of character 's' :  6
Index Positions of 's' are :  [3, 6, 10, 17, 30, 47]
**** Find Occurrence count and index position of a multiple character in a String **** 
Total Occurrence Count of characters 's' , 'a' and 'c' are :  12
Index Positions of  s  are :  [3, 6, 10, 17, 30, 47]
Index Positions of  a  are :  [8, 11, 24, 28, 31]
Index Positions of  c  are :  [37]

 

 

Subscribe with us to join a list of 2000+ Programmers for weekly newsletter.