This is a question that sometimes comes up in an interview: Can you count the number of times characters occur in a string?
my_string = “Happy New Year!”
One quick way to do it in Python is by using set iteration:
>>> from pprint import pprint
>>> my_string = "Happy New Year!"
>>> char_set = {c + " : " + str(my_string.count(c)) for c in my_string if c.isalpha()}
>>> pprint(char_set)
set(['H : 1',
'N : 1',
'Y : 1',
'a : 2',
'e : 2',
'p : 2',
'r : 1',
'w : 1',
'y : 1'])
>>>
Sometimes interviewers don’t like set iteration, or just want you to use a different method.
You can use a dictionary:
>>> from pprint import pprint
>>> my_string = "Happy New Year!"
>>> my_dict = {}
>>> for c in my_string:
... if not c.isalpha():
... continue
... if not c in my_dict:
... my_dict[c] = 1
... continue
... my_dict[c] += 1
...
>>> pprint(my_dict)
{'H': 1, 'N': 1, 'Y': 1, 'a': 2, 'e': 2, 'p': 2, 'r': 1, 'w': 1, 'y': 1}
>>>