Find the occurrence of each character in string using python
Contents
Method 1: Count function :
The count function is used to count the occurrence of each character in string. Here we can give the specific character in count function and it will return the number of occurrence in that string.
Example :
>> sample_string = “hello world”
>>> sample_string.count(‘h’)
Output: 1
Method 2 : Get the all character occurrence in string using dictionary
Here the dictionary variable (example : all_freq ={}) used to store the each character occurrence of the input string.The for loop is iterate each character in the input string and count the frequency of character and store the results in the dictionary variable.
Example
1 2 3 4 5 6 7 8 9 10 |
def multi_repeat(word): all_freq = {} for i in word: if i in all_freq: all_freq[i] +=1 else: all_freq[i] = 1 print("Count of occurrence :\n" + str(all_freq)) multi_repeat("xxyxyaaxabc") |
Output :
Count of occurrence :
{‘x’: 4, ‘y’: 2, ‘a’: 3, ‘b’: 1, ‘c’: 1}
Python program to print the required character based on character occurrence
We can validate the each character occurrence in string and print the required character alone by validate the counter value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
def multi_repeat(word,k): print ('Occurence of each character in string') final_str="" all_freq = {} for i in word: if i in all_freq: all_freq[i] +=1 else: all_freq[i] = 1 print("Count of occurence :\n" + str(all_freq)) for key in all_freq: value = all_freq[key] if value>=k: final_str+=key print(key,":",value) print("Final output:" + final_str) multi_repeat("xxyxyaaxabc",2) |
Output: