Basically there are multiple steps involved:
- Getting rid of the chars that you don't want to count
- Count the remaining
You have several options available to do these. I'll just present one option, but keep in mind that there might be other (and better) alternatives.
from collections import Counter
the_input = input('Enter something')
Counter(char for char in the_input.upper() if char.isalpha())
For example:
Enter something: aashkfze3f8237rhbjasdkvjuhb
Counter({'A': 3,
'B': 2,
'D': 1,
'E': 1,
'F': 2,
'H': 3,
'J': 2,
'K': 2,
'R': 1,
'S': 2,
'U': 1,
'V': 1,
'Z': 1})
So it obviously worked. Here I used collections.Counter
to count and a generator expression using str.isalpha
as condition to get rid of the unwanted characters.
Note that there are several bad habits in your code that will make your life more complicated than it needs to be:
dict = {}
will shadow the built-in dict
. So it's better to choose a different name.
string
is the name of a built-in module, so here a different name might be better (but not str
which is a built-in name as well).
stringUpper = string.upper()
. In Python you generally don't use camelCase but use _
to seperate word (i.e. string_upper
) but since you only use it to loop over you might as well use for n in string.upper():
directly.
- Variable names like
n
aren't very helpful. Usually you can name them char
or character
when iterating over a string or item
when iterating over a "general" iterable.