Change language

Python | Counting occurences of a character in a string

| | |

Method # 1: The Naive Method

Iterate the entire string for that particular character, then increment the counter when we encounter that particular character.

# Python3 demo code
# frequency of occurrence using
# naive method

  
# initializing string

test_str = "GeeksforGeeks"

 
# using a naive counting method
# counting e

count = 0

  

for i in test_str:

if i = = ’e’ :

count = count + 1

 
# print result

print ( "Count of e in Python.Engineering is:"

+   str ( count))

 

Output:

 Count of e in Python.Engineering is: 4 

Method # 2: Using count()

Using count () — the most common method in Python to get the occurrence of any item in any container. It is easy to code and remember and therefore quite popular.

# Python3 demo code
# frequency of occurrence using
# count ()

 
# initializing string

test_str = "GeeksforGeeks"

 
# using count () to get the score
# counting e

counter = test_str.count ( ’e’ )

  
# print result

print ( "Count of e in Python.Engineering is:"

+   str (counter))

Output:

 Count of e in Python.Engineering is: 4 

Method # 3: Using collections.Counter()

This is a lesser known method to get the entry of an element into any container in Python. This also performs a task similar to the above two methods, it is just a function of another library i.e. collections.

# Python3 demo code
# frequency of occurrence using
# collection.Counter ()

from collections import Counter

  
# initializing string

test_str = "GeeksforGeeks"

 
# using collection.Counter () to count
# counting e

count = Counter (test_str)

  
# print result

print ( "Count of e in Python.Engineering is:"

+   str (count [ ’ e’ ]))

Output:

 Count of e in Python.Engineering is: 4 

Method # 4: Using lambda + sum () + map()

Lambda functions with sum () and map () can solve this particular problem of counting the total number of occurrences of a certain element in a string. It uses sum () to sum all occurrences from map () .

# Python3 demo code
# frequency of occurrence using
# lambda + sum () + map ( )

 
# initialization string

test_str = "GeeksforGeeks"

 
# using lambda + sum () + map () to count
# counting e

count = sum ( map ( lambda x: 1 if ’e’ in x else 0 , test_str))

 
# print result

print ( "Count of e in Python.Engineering is:"

+   str (count))

Output:

 Count of e in Python.Engineering is: 4 

Method # 5: Using re + findall ()

Regular Expressions can help us solve many problems of coding ania associated with strings. They can also help us achieve the task of finding the occurrence of an element in a string.

# Python3 demo code
# frequency of occurrence using
# re + findall ()

import re

 
# initialization string

test_str = "GeeksforGeeks"

 
# using re + findall () to count
# counting e

count = len (re.findall ( "e" , test_str))

 
# print result

print ( "Count of e in Python.Engineering is:"

+   str (count))

Output:

 Count of e in Python.Engineering is: 4 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically