Count Vowels in String Python

Counting the number of unique vowels in a string

I think you're overcomplicating things. To get the number of unique vowels, you can lowercase the entire string, then call set() on the lowercased string to get a set of unique letters. You can then check whether each vowel is in this set. If it is, it appears in the text, otherwise it doesn't:

def count_vowels(text):
letters = set(text.lower())

count = 0
for vowel in 'aeiou':
if vowel in letters:
count += 1
return count

print(count_vowels("Aaa aeeE")) # Prints 2
print(count_vowels("eiOuayOI j_#Ra")) # Prints 5

If you prefer a one-liner, you can do this:

def count_vowels(text):
return sum(1 for vowel in 'aeiou' if vowel in set(text.lower()))

or this (as suggested by psmears):

def count_vowels(text):
return len(set(text.lower()) & set('aeiou'))

Python function that will find and count vowels in a given string

Try like this:

def findVowels(txt):
return sum(1 for t in txt if t in 'aeiouy')

How to count vowels and consonants in Python

def classify_letter(string: str):
vowels = 0
consonants = 0
for i in string:
if i.casefold() in 'aeiou':
vowels += 1
elif i.casefold() in 'qwrtypsdfghjklzxcvbnm':
consonants += 1
return vowels, consonants

or with a list comprehension

def classify_letter(strng: str) -> tuple:
x = [i.casefold() in "aeiou" for i in strng if i.casefold() in string.ascii_lowercase]
return x.count(True), x.count(False)

^ I acknowledge this might not be the best way to implement that, im open to suggestions to make it shorter and optimized!

when passed "hello-" these both return:

(2,3)

Count vowels of each word in a string

You can flag the vowels using translate to convert all the vowels to 'a's . Then count the 'a's in each word using the count method:

sentence = "computer programmers rock"

vowels = str.maketrans("aeiouAEIOU","Count Vowels in String Pythonaa")
flagged = sentence.translate(vowels) # all vowels --> 'a'
counts = [word.count('a') for word in flagged.split()] # counts per word
score = sum(1 if c<=2 else 2 for c in counts) # sum of points

print(counts,score)
# [3, 3, 1] 5

Python def vowelCount() counting the number of vowels

I think it's the problem of your indenting. return should be the same indent as for.
As for the number checking, you can simply use userinput.isalpha(). This checks if every element in the string is in the alphabet.



Related Topics



Leave a reply



Submit