Count occurrences of each character in string Python
In this post, you will learn how to count occurrences of each character in a string using the Python programming language. These techniques find out how many times a given character is repeated in a given string.
Count each character in string Python using range and len
We use a for loop to match the character with each character present in the string, which is accessed by the index value. The range and len work encourage us to decide how frequently the coordinating must be done while moving from left to right of the string. The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number, while the len() function returns the length of the string.
str = "precaution is better than cure"
char = 'e'
# Print Given String and Character
print("String:\n", str)
print("Character:\n", char)
res = 0
for i in range(len(str)):
# Matching character in string
if (str[i] == char):
res = res + 1
print("Count occurrences of given character in string:\n",res)
Output of the above code-
String:
precaution is better than cure
Character:
e
Count occurrences of given character in string:
4
Count each character in string Python using Counter
Python Counter is a holder that will hold the count of each of the elements present in the container. The counter is a sub-class accessible inside the dictionary class. It works by putting each character as a key and counting them as dictionary values. The Counter class sets linear time to pre-measure the string and offers consistent time-counting tasks. However, it consumes some space to store the frequency of each character.
from collections import Counter
str = "precaution is better than cure"
char = 't'
# Print Given String and Character
print("String:\n", str)
print("Character:\n",char)
count = Counter(str)
print("Count occurrences of given character in string:\n",count['t'])
Output of the above code-
String:
precaution is better than cure
Character:
t
Count occurrences of given character in string:
4
Count each character in string Python using dictionary
In the above example, we have found the count of the occurrences of a particular character in a string. Here, we have explained how to count the occurrences of each character in a string. Python has an in-built dictionary called dict, which we can use to create an arbitrary definition of a character string. The dict() is a constructor which is used to create instances of the class dict. The method dict.get() returns the value of the item with the specified key. It means it stores each character as dictionary keys and their counts as dictionary values.
# initializing string
x = "precaution is better than cure"
res = {}
# iterating over the string
for keys in x:
res[keys] = res.get(keys, 0) + 1
# printing result
print ("Count occurrences of each character in string:"
+ str(res))
Output of the above code-
Count occurrences of each character in string:
{'p': 1, 'r': 3, 'e': 4, 'c': 2, 'a': 2, 'u': 2, 't': 4, 'i': 2, 'o': 1, 'n': 2, ' ': 4, 's': 1, 'b': 1, 'h': 1}
Related Articles
Python remove punctuation from string
Python split string by comma
Count vowels in a string Python
Count consonants in a string Python
Vader Sentiment Analysis Python
isalpha Python
Python YouTube Downloader Script
Python project ideas for beginners
Pandas string to datetime
Fillna Pandas Example
Lemmatization nltk
How to generate QR Code in Python using PyQRCode
OpenCV and OCR Python
PHP code to send SMS to mobile from website
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml