Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the occurrence of characters in a string

Tags:

python

string

I'm being asked to count the occurrence of letters and spaces and punctuation characters in a string from user input and and in the printout the letters should appear in order in which they appear in the text, but no letter should appear twice and also lowercase and uppercase should be counted as one. my code so far looks like this.

S = str(input("Enter a string: "))
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "

for char in S:
     if char in alpha:
          count = S.count(char)
     print(char,':',count)

output

Enter a string: hello
h : 1
e : 1
l : 2
l : 2
o : 1

i want it to look like this

Enter a string: hello
    h : 1
    e : 1
    l : 2
    o : 1

i was thinking if i turned the string and the the count of occurred chars into a nested list like

Enter a string: hello
[['h', 1], ['e', 1], ['l', 2], ['l', 2], ['o', 1]]

could i remove the list that are the same and leave just one?

like image 927
Mike Avatar asked Nov 04 '25 21:11

Mike


2 Answers

>>> s = 'hello'
>>> s = s.lower()
>>> print('\n'.join('{} : {}'.format(c, s.count(c)) for i, c in enumerate(s) if c in "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! " and c not in s[:i]))
h : 1
e : 1
l : 2
o : 1
like image 200
John1024 Avatar answered Nov 07 '25 16:11

John1024


This is a classic situation for using Counter of the collections module:

from collections import Counter

S ='hello'
S = S.lower()
d = Counter(S)
for item, ct in d.items():
    print '%s occured %d times' % (item, ct)
like image 40
Saksham Varma Avatar answered Nov 07 '25 15:11

Saksham Varma