Python program to find occurrence to each character in given string
Last Updated :
29 Mar, 2023
Given a string, the task is to write a program in Python that prints the number of occurrences of each character in a string. There are multiple ways in Python, we can do this task. Let's discuss a few of them.
Method #1: Using set() + count() Iterate over the set converted string and get the count of each character in original string.
Python3
# Python3 code to program to find occurrence
# to each character in given string
# initializing string
inp_str = "GeeksforGeeks"
# using set() + count() to get count
# of each element in string
out = {x : inp_str.count(x) for x in set(inp_str )}
# printing result
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(out))
OutputOccurrence of all characters in GeeksforGeeks is :
{'o': 1, 's': 2, 'e': 4, 'G': 2, 'r': 1, 'f': 1, 'k': 2}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using dictionary
Python3
# Python3 code to program to find occurrence
# to each character in given string
# initializing string
inp_str = "GeeksforGeeks"
# frequency dictionary
freq = {}
for ele in inp_str:
if ele in freq:
freq[ele] += 1
else:
freq[ele] = 1
# printing result
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(freq))
OutputOccurrence of all characters in GeeksforGeeks is :
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using collections
Python3
# Python3 code to program to find occurrence
# to each character in given string
from collections import Counter
# initializing string
in_str = "GeeksforGeeks"
# using collections.Counter() to get
# count of each element in string
oup = Counter(in_str)
# printing result
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(oup))
OutputOccurrence of all characters in GeeksforGeeks is :
Counter({'e': 4, 'G': 2, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1})
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using Iteration and get method
This code is finding the number of occurrences of each character in the string . It does this by iterating through the characters in the string, and keeping a count of each character in a dictionary called "freq". For each character, it increments the count of that character in the dictionary by 1. At the end, it prints the dictionary containing the counts of each character.
Python3
#Python3 code to program to find occurrence
#to each character in given string
#initializing string
inp_str = "GeeksforGeeks"
#frequency dictionary
freq = {}
for ele in inp_str:
freq[ele] = freq.get(ele, 0) + 1
#printing result
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(freq))
#This code is contributed by Edula Vinay Kumar Reddy
OutputOccurrence of all characters in GeeksforGeeks is :
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}
Time Complexity: The time complexity of this code is O(n), where n is the length of the input string. This is because the for loop iterates through all elements of the string and the get() method has a time complexity of O(1).
Auxiliary Space: The space complexity of this code is O(k), where k is the number of unique characters in the input string. This is because the frequency dictionary stores the count for each unique character in the string.
Method: Using the setdefault() method
- A dictionary freq is defined.
- for loop is used to iterate over each character in the string "GeeksForGeeks".
- the setdefault() method is used to set the value of character in the dictionary to 0 if it does not exist already.
- Then, the value of the character in the dictionary is incremented by 1.
- After the loop completes, the freq dictionary contains the occurrence of each character in a string.
Python3
string = "GeeksForGeeks"
freq = {}
for char in string:
freq.setdefault(char, 0)
freq[char] += 1
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(freq))
OutputOccurrence of all characters in GeeksforGeeks is :
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'F': 1, 'o': 1, 'r': 1}
Time Complexity: O(n) as we are the traversing the completes string where n is the length of the string
Auxiliary Space: O(K) The space complexity of this code is O(k), where k is the number of unique characters in the input string. This is because the frequency dictionary stores the count for each unique character in the string.
Method #6 : Using operator.countOf() method
Approach
- Get unique characters from string by using list(),set() methods
- Create a new dictionary with key as unique value and count of unique value in original string as value using operator.countOf() method
- Display the dictionary
Python3
# Python3 code to program to find occurrence
# to each character in given string
# initializing string
inp_str = "GeeksforGeeks"
x=list(set(inp_str))
out = dict()
import operator
for i in x:
out[i]=operator.countOf(inp_str,i)
# printing result
print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(out))
OutputOccurrence of all characters in GeeksforGeeks is :
{'G': 2, 'k': 2, 's': 2, 'e': 4, 'r': 1, 'o': 1, 'f': 1}
Time Complexity: O(n) as we are the traversing the completes string where n is the length of the string
Auxiliary Space: O(K) The space complexity of this code is O(k), where k is the number of unique characters in the input string. This is because the frequency dictionary stores the count for each unique character in the string.
Similar Reads
Python program to extract characters in given range from a string list
Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best",
4 min read
Python - Count occurrences of each word in given text file
Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the w
4 min read
Python - Characters Index occurrences in String
Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
6 min read
Find position of a character in given string - Python
Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
2 min read
Python program to find the most occurring character and its count
Given a string, write a python program to find the most occurrence character and its number of occurrences. Examples: Input : hello Output : ('l', 2) Input : geeksforgeeks Output : ('e', 4) We can solve this problem quickly in python using Counter() method. Simple Approach is to 1) Create a dictiona
3 min read
Python program to find the occurrence of substring in the string
Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is
4 min read
Python program to Extract string till first Non-Alphanumeric character
Given a string, extract all the alphanumerics before 1st occurrence of non-alphanumeric. Input : test_str = 'geek$s4g!!!eeks' Output : geek Explanation : Stopped at $ occurrence. Input : test_str = 'ge)eks4g!!!eeks' Output : ge Explanation : Stopped at ) occurrence. Method #1 : Using regex + search(
4 min read
Python - Extract String after Nth occurrence of K character
Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e"
7 min read
Python | Get the string after occurrence of given substring
The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python.Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 min read
Python Program to Extract Strings with at least given number of characters from other list
Given a list containing only string elements, the task is to write a Python program to extract all the strings which have characters from another list given a number of times. Examples: Input : test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"], char_list = ['e', 't', 's', 'm', 'n'], K = 2
7 min read