#this function takes in a string and returns the number of characters of each letter of the alphabet that are #inside of the string def my_function(my_string): #make the string lowecase for easier comparison lowercase_my_string = my_string.lower() #this list is used to keep track of the entire alphabet alpha_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] #this list is used to be the comparator to the alpha_list and increment themselves from 0 number_list = [] for i in range(26): number_list.append(0) #this list is returned at the end and is a list of readable strings that will return in the format of #There are {number} {character}'s in this string. number_in_alpha_list = [] #this is the logic loop for the program, the first step is to loop through the provided string, easy enough for string_char in lowercase_my_string: #then for each character in the string we need to loop through the alphabet in the alpha_list for alphabet_char in alpha_list: #this is the complicated part, so we make a comparison from the character in the string to the character in the alphabet #and if they are equal, we increment the equivalent value in the number_list #for example: the first character called in my_function below is h, and h is at index 7 in the aplha_list #so we increment number_list[7] = 1 if string_char == alphabet_char: number_list[alpha_list.index(alphabet_char)]+=1 #Apparently there is no way to keep track of the index in a normal for loop, so I had to use this enumerate function to keep track of the index #it does the exact same thing as a for loop, but also keeps track of the index which is critical to getting the correct character out of the alpha_list for index, num in enumerate(number_list): if num > 0: if num == 1: number_in_alpha_list.append("There is {number} {character} in this string".format(number = num, character = alpha_list[index])) else: number_in_alpha_list.append("There are {number} {character}'s in this string".format(number = num, character = alpha_list[index])) #and at the end we return the list of strings and we can do what we wish with that list when we return it, I just print it out return number_in_alpha_list print my_function("hello devin");
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question