Method # 1: The Naive Method
Iterate the entire string for that particular character, then increment the counter when we encounter that particular character.
|
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.
|
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.
|
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 ()
.
|
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.
|
Output:
Count of e in Python.Engineering is: 4