I'm a Python newbie, taking a class. I have to find out how many times each letter appears in a string. I've seen all the responses about .count and counter, but this has not been covered yet. I took my string and created a list of the characters so they only appeared once. Then I tried to count how many times the character from the list appears in the string, and I just can't get it to work. I know how to check for a specific letter, but I can't make it check for each letter in my list. Program is below (there are some extra codes, but I'm using them to make sure it's counting properly).
# CONSTANTS and Blank Lists
letter_list = []
count = 0
letter_count = []
index = 0
# Begin programming
my_string = 'SUKI IS SWEET'
for ch in my_string:
if ch not in letter_list:
letter_list.append(ch)
print(letter_list)
print()
for ch in my_string:
if letter_list[index] == ch:
count = count + 1
letter_count.append(count)
# Double-checks to make sure running properly
print(letter_list[0],'appears',letter_count[0], 'times')
print()
print(letter_count)
print()
When I run this, I get the proper answer: ['S', 'U', 'K', 'I', ' ', 'W', 'E', 'T'] (my letter_list) S appears 3 times (S does appear 3 times) [3] (my letter_count)
However, I KNOW that my letter_count.append is in the wrong place. But if I move it in, it gets jacked up. And the moment I try to move it along by increasing the index, it blows up (see below):
# CONSTANTS and Blank Lists
letter_list = []
count = 0
letter_count = []
index = 0
# Begin programming
my_string = 'SUKI IS SWEET'
for ch in my_string:
if ch not in letter_list:
letter_list.append(ch)
print(letter_list)
print()
for ch in my_string:
if letter_list[index] == ch:
count = count + 1
letter_count.append(count)
index = index + 1
# Double-checks to make sure running properly
print(letter_list[0],'appears',letter_count[0], 'times')
print()
print(letter_count)
print()
RESULTS: Traceback (most recent call last): File "C:\Users\Rogue\Desktop\TEST_2.py", line 30, in main() File "C:\Users\Rogue\Desktop\TEST_2.py", line 18, in main if letter_list[index] == ch: IndexError: list index out of range
I know I'm messing this up bad. But no matter what I do, I can't seem to get this to work. Please help!
sortedfunction, or the list.sortmethod?