Python : Count number of occurrences of a character in string
This tutorial guides you on how to count number of occurrences of a character in a given string. This logic would be very useful when you wanted to remove duplicates or checking unwanted characters from the string in Python programming.
Python : Count number of occurrences of a character in string
There are numerous options available in Python programming to count the number of occurrences of a character in string. In the first section we are going to see how to use String count().Â
Python String count()
The count() method of Python string returns the number of occurrences of a substring in the given string. Let’s say you wanted to find the number of times the character ‘s’ repeated in the string “sneppets“. This is easy method when compared to other approaches, hence it is quite popular.
For example,
mystr = "sneppets" mystr.count('s')
Output
2
Using Counter Class of collections library
This is less commonly used approach compared to the String count() method. But you can use Counter class of collections library which also performs similar logic as in the above approach.
For example, to count the number of occurrence of character “s” in string “sneppets” using Counter class.
from collections import Counter mystr = 'sneppets' c = Counter(mystr) c['s']
Output
2
Using for loop and count
This is native approach which uses for loop and the counter. Here we need to iterate the given string and check each single character in the string for a particular character. If the character is found then increase the counter. The value of the count is the number of occurrence of that particular character.
For example,
mystr = "sneppets" count = 0 for element in mystr: if (element == 's'): count = count + 1 count
Output
2
Number of occurrences of all characters in a given string
This approach will give you an output which prints all the unique characters and the number of occurrences of each character at one shot.
For example,
def getcount(str): countval = {} for element in set(str): countval[element] = str.count(element) return countval
Let’s pass input string to getcount() method.
getcount("sneppets")
Output
The output prints the number of times each character repeated in the given string.
{'p': 2, 't': 1, 'n': 1, 'e': 2, 's': 2}
Using List Comprehension
You can also use list comprehension in the above getcount() method which will give you the similar output.
def getcount(str): return {element: str.count(element) for element in set(str)}
Output
getcount("sneppets") {'p': 2, 't': 1, 'n': 1, 'e': 2, 's': 2}
That’s it. You had learnt various approaches for finding the count of characters that are repeated in the given string.
Hope it is helpful 🙂
You’ll also like:
- Convert list of lists to flat list – flatten list in Python ?
- Concatenate or join two lists using Python
- Single digit number to double digits string conversion in Python
- String Immutability with Examples in Python
- Python Program to Check Given Number is Odd or Even
- Increase the cell width of the Jupyter Notebook in browser
- Add python3 kernel to jupyter IPython notebook ?
- Programs to Print Patterns – Pyramid, Triangle using Star
- How to change the default theme in Jupyter Notebook ?
- Change the Jupyter Notebook startup folder in Windows & Mac
- Get number of elements in a list – Python ?
- Get the first and last element of a list in Python ?
- Count the number of occurrences of a list item in Python ?
- Python equivalent for && (logical and) to use in if statement
- Split list in to chunks of size n in Python
- How to check if the given list is empty in Python ?
- Remove non-numeric characters from string in Python
- Count the number of occurrences of a list item in Python ?
- Convert negative to positive number in Python
- Create list of lists in Python
- Extract numbers from a string in python
- How to access index and value in for loop – Python?
- Find index of an element in a list – Python
- Prevent the list that changes unexpected after assignment – Python ?