0

I am trying to write a simple piece of code that checks how many times each of the letters: a,e,i,o,u exists in a string but i am getting the error: string index out of range. what can I do to fix that? the code is:

def targ6(str6):
  x = ['a','e','i','o','u']
  s = ""
  for tav in str6:
    for y in range(len(x)):
      if x[y] == tav:
        s[y] += 1
  for y in range(len(x)):
    return ('the letter'+x[tav]+'appears'+s[tav]+'times')


#main
string6=input("enter a string")
print(targ6(string6))
oron
  • 11
  • 1

3 Answers3

1

Try this:

def targ6(str6):
  x = ['a','e','i','o','u']
  s = {k:0 for k in x}
  for tav in str6:
    for y in range(len(x)):
      if x[y] == tav:
        s[tav] += 1 # s[x[y]] += 1
  return s


#main
string6="enter a string"
print(targ6(string6))

Output:

{'a': 1, 'e': 2, 'i': 1, 'o': 0, 'u': 0}
dimay
  • 2,768
  • 1
  • 13
  • 22
0
from collections import Counter

def targ6(str6):
    list1 = []
    x = ['a','e','i','o','u']
    for i in str6:  #For character in string
        if i in x:     #If character in vowel list
            list1.append(i)       #Append the character to a list

    for k, v in Counter(list1).items(): #Counter returns a dict with each element's count
        print(k, "appears", v, "times in", str6)
string6 = input("enter a string :")
targ6(string6)

Example:-

enter a string :Hi How are you? Fine?
i appears 2 times in Hi How are you? Fine?
o appears 2 times in Hi How are you? Fine?
a appears 1 times in Hi How are you? Fine?
e appears 2 times in Hi How are you? Fine?
u appears 1 times in Hi How are you? Fine?
Abhishek Rai
  • 2,159
  • 3
  • 18
  • 38
0
  • You cannot modify strings (like s) in place in Python, and they definitely don't work like a counter or something.
  • If you ever find yourself writing for ... in range(len(...)) in Python, stop what you're doing. There is going to be a better way.
  • A function can only return once. Since you're going to print something out anyway I took the liberty of exchanging the return for a print.
  • Use the builtin functions and methods! Read the Python documentation over, it's pretty accessible and you don't have to remember everything, just get a feel for things so you know where to look in the future.
def count_vowels(string):
    for vowel in 'aeiou':
        print('the letter', vowel, 'appears', string.count(vowel), 'times')

input_string = input("enter a string: ")
count_vowels(input_string)
Jasmijn
  • 9,370
  • 2
  • 29
  • 43