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?
>>> 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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With