number of occurrence counting in a string

0 votes
Write a function called number_of_occurrences that takes in a string and outputs the the number of occurrences that a character shows up in a dictionary. This dictionary should be ordered by the number of occurrences in descending order. You can ignore spacing, capitalization, and punctuation.
May 16, 2020 in Python by Anny
• 120 points

Hey, @Anny,

You can try this:

from collections import Counter 

# initializing string 

test_str = "Pythonforall"

# using collections.Counter() to get  

# count of each element in string 

res = Counter(test_str) 

# printing result  

print ("Count of all characters in Pythonforall is :\n "

                                           +  str(res))

Count of all characters in Pythonforall is :
Counter({'o': 2, 'l': 2, 'a': 1, 'f' : 1, 'h': 1, 'n' : 1, 'p': 1, 'r': 1, 't': 1, 'y' : 1})

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.

Related Questions In Python

0 votes
3 answers

Count the number occurrences of a character in a string

The string count() method returns the number of occurrences of ...READ MORE

answered Dec 28, 2020 in Python by Carlos
0 votes
2 answers

How to calculate square root of a number in python?

calculate square root in python >>> import math ...READ MORE

answered Apr 2, 2019 in Python by anonymous
0 votes
2 answers

Finding the index of a character in python string

You can use word.find('o') as well to ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
+1 vote
2 answers

How to print first character of each word in upper case of a string in Python

class Solution:     def firstAlphabet(self, s):             self.s=s              k=''              k=k+s[0]              for i in range(len(s)):                     if ...READ MORE

answered Oct 28, 2020 in Python by Anurag
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,440 points
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29, 2019 in Python by rajesh
• 1,230 points
+4 votes
1 answer

Print the odd and even factors of a number in Python

x = int(input("Enter any number \n")) print("The factors ...READ MORE

answered Nov 19, 2018 in Python by Nabarupa
–1 vote
2 answers
0 votes
3 answers

Python program to print occurrence of character in string

Try below code string = input("Enter a string: ...READ MORE

answered May 28, 2020 in Python by Anubhav
• 260 points
+1 vote
1 answer