简体   繁体   中英

Counting number of vowels in a string in Python

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?

I would do something like

def countvowels(st):
  return len ([c for c in st if c.lower() in 'aeiou'])

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

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

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)])

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")]

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)

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM