 # Python – Count occurrences of a character in string

## Python | Count occurrences of a character in string

Given a string, the task is to count the frequency of a single character in that string. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters.

Method #1 : Naive method

Iterate the entire string for that particular character and then increase the counter when we encounter the particular character.

 `# Python3 code to demonstrate ` `# occurrence frequency using ` `# naive method ` ` ` `# initializing string ` `test_str ``=` `"GeeksforGeeks"` ` ` `# using naive method to get count ` `# counting e ` `count ``=` `0` ` ` `for` `i ``in` `test_str:` `    ``if` `i ``=``=` `'e'``:` `        ``count ``=` `count ``+` `1` ` ` `# printing result ` `print` `(``"Count of e in GeeksforGeeks is : "` `                            ``+`  `str``(count))`

Output :

`Count of e in GeeksforGeeks is : 4`

Method #2 : Using `count()`

Using `count()` is the most conventional method in Python to get the occurrence of any element in any container. This is easy to code and remember and hence quite popular.

 `# Python3 code to demonstrate ` `# occurrence frequency using ` `# count()` ` ` `# initializing string ` `test_str ``=` `"GeeksforGeeks"` ` ` `# using count() to get count ` `# counting e ` `counter ``=` `test_str.count(``'e'``)` ` ` `# printing result ` `print` `(``"Count of e in GeeksforGeeks is : "` `                           ``+`  `str``(counter))`

Output :

```Count of e in GeeksforGeeks is : 4
```

Method #3 : Using `collections.Counter()`

This is the lesser known method to get the occurrence of the element across any container in Python. This also performs the task similar to above two method, just is a function of a different library i.e collections.

 `# Python3 code to demonstrate ` `# occurrence frequency using ` `# collections.Counter()` `from` `collections ``import` `Counter` ` ` `# initializing string ` `test_str ``=` `"GeeksforGeeks"` ` ` `# using collections.Counter() to get count ` `# counting e ` `count ``=` `Counter(test_str)` ` ` `# printing result ` `print` `(``"Count of e in GeeksforGeeks is : "` `                       ``+`  `str``(count[``'e'``]))`

Output :

```Count of e in GeeksforGeeks is : 4
```

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

Lambda functions, along with `sum()` and` map()` can achieve this particular task of counting the total occurrences of particular element in a string. This uses` sum()` to sum up all the occurrences obtained using` map()`.

 `# Python3 code to demonstrate ` `# occurrence frequency using ` `# lambda + sum() + map()` ` ` `# initializing string ` `test_str ``=` `"GeeksforGeeks"` ` ` `# using lambda + sum() + map() to get count ` `# counting e ` `count ``=` `sum``(``map``(``lambda` `x : ``1` `if` `'e'` `in` `x ``else` `0``, test_str))` ` ` `# printing result ` `print` `(``"Count of e in GeeksforGeeks is : "` `                            ``+`  `str``(count))`

Output :

```Count of e in GeeksforGeeks is : 4
```

Method #5 : Using `re + findall()`

Regular Expressions can help us to achieve many coding tasks related to strings. They can also facilitate us in achieving the task of finding the occurrence of element in string.

 `# Python3 code to demonstrate ` `# occurrence frequency using ` `# re + findall()` `import` `re` ` ` `# initializing string ` `test_str ``=` `"GeeksforGeeks"` ` ` `# using re + findall() to get count ` `# counting e ` `count ``=` `len``(re.findall(``"e"``, test_str))` ` ` `# printing result ` `print` `(``"Count of e in GeeksforGeeks is : "` `                            ``+`  `str``(count))`

Output :

```Count of e in GeeksforGeeks is : 4
```

Last Updated on October 25, 2021 by admin

## Python OpenCV – cv2.rotate() methodPython OpenCV – cv2.rotate() method

Python OpenCV – cv2.rotate() method OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.rotate() method is used to rotate a 2D array in multiples of 90 degrees. The function cv::rotate rotates the array in three different ways. Syntax: cv2.cv.rotate(

## Python – Check if a given object is list or notPython – Check if a given object is list or not

Python – Check if a given object is list or not Given an object, the task is to check whether the object is list or not. Method #1: Using isinstance # Python code to demonstrate # check whether the object

## Python – Call function from another functionPython – Call function from another function

Python – Call function from another function In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we

## Python Input Methods for Competitive ProgrammingPython Input Methods for Competitive Programming

Python Input Methods for Competitive Programming Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. Online coding platforms, if C/C++ limit provided is X. Usually, in

## How to convert timestamp string to datetime object in Python?How to convert timestamp string to datetime object in Python?

How to convert timestamp string to datetime object in Python? Python has a module named DateTime to work with dates and times. We did not need to install it separately. It is pre-installed with the python package itself. A UNIX timestamp is

## Python – Create list of numbers with given rangePython – Create list of numbers with given range

Python | Create list of numbers with given range Given two numbers r1 and r2 (which defines the range), write a Python program to create a list with the given range (inclusive). Examples: Input : r1 = -1, r2 =

## Generate a graph using Dictionary in PythonGenerate a graph using Dictionary in Python

Generate a graph using Dictionary in Python In this article, we will see how to implement graph in python using dictionary data structure in python. The keys of the dictionary used are the nodes of our graph and the corresponding values are

## Python Dictionary keys() methodPython Dictionary keys() method

Python Dictionary keys() method Dictionary in Python is a collection of data values which only maintains the order of insertion, used to store data values like a map, which, unlike other Data Types that hold only a single value as