1

Okay so what I did was

def countvowels(st):
    result=st.count("a")+st.count("A")+st.count("e")+st.count("E")+st.count("i")+st.count("I")+st.count("o")+st.count("O")+st.count("u")+st.count("U")
    return result

This works(I'm aware indentation might be wrong in this post, but the way I have it indented in python, it works).

Is there a better way to do this? Using for loops?

2

7 Answers 7

1

I would do something like

def countvowels(st):
  return len ([c for c in st if c.lower() in 'aeiou'])
Sign up to request clarification or add additional context in comments.

1 Comment

sum(c.lower() in 'aeiou' for c in st) saves making a temporary list
1

There's definitely better ways. Here's one.

   def countvowels(s):
      s = s.lower()
      return sum(s.count(v) for v in "aeiou")

Comments

0

You can do that using list comprehension

def countvowels(w):
    vowels= "aAiIeEoOuU"
    return len([i for i in list(w) if i in list(vowels)])

1 Comment

You don't need the list constructors. Strings are iterable in python.
0

You could use regex pattern to do this easily. But it looks to me, that you want to do it without. So here is some code to do so:

string = "This is a test for vowel counting"
print [(i,string.count(i)) for i in list("AaEeIiOoUu")]

Comments

0

you can do it in various ways, first look in google before asking, i had copy pasted 2 of them

def countvowels(string):
    num_vowels=0
    for char in string:
        if char in "aeiouAEIOU":
           num_vowels = num_vowels+1
    return num_vowels

data = raw_input("Please type a sentence: ")
vowels = "aeiou"
for v in vowels:
    print v, data.lower().count(v)

Comments

0

You can also try Counter from collections (only available from Python 2.7+) as shown below . It'll show how many times each letter has been repeated.

from collections import Counter
st = raw_input("Enter the string")
print Counter(st)

But you want vowels specifically then try this.

import re

def count_vowels(string):
    vowels = re.findall('[aeiou]', string, re.IGNORECASE)
    return len(vowels)

st = input("Enter a string:")
print count_vowels(st)

Comments

0

Here is a version using map:

phrase=list("This is a test for vowel counting")
base="AaEeIiOoUu"
def c(b):
    print b+":",phrase.count(b)
map(c,base)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.