-1

I'm a bit confused with the counting of a string that I would enter manually. I am basically trying to count the number of words and the number of characters without spaces. Also if it would be possible, who can help with counting the vowels?

This is all I have so far:

vowels = [ 'a','e','i','o','u','A','E','I','O','U']
constants= ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']

s= input ('Enter a Sentence: ')

print ('Your sentence is:', s)

print ('Number of Characters', len(s));

print ('Number of Vowels', s);
jwodder
  • 54,758
  • 12
  • 108
  • 124
The Beginning
  • 13
  • 1
  • 6
  • this helps http://stackoverflow.com/questions/20226110/detecting-vowels-vs-consonants-in-python – neiesc Oct 29 '14 at 23:32

3 Answers3

2
s = input("Enter a sentence: ")

word_count = len(s.split()) # count the words with split
char_count = len(s.replace(' ', '')) # count the chars having replaced spaces with ''
vowel_count = sum(1 for c in s if c.lower() in ['a','e','i','o','u']) # sum 1 for each vowel

more info:

on str.split: http://www.tutorialspoint.com/python/string_split.htm

on sum:

sum(sequence[, start]) -> value

Return the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the sequence is
empty, return start.

on str.replace: http://www.tutorialspoint.com/python/string_replace.htm

Totem
  • 7,189
  • 5
  • 39
  • 66
  • If this solution solved your issue, please consider accepting it as the official answer(the tick mark next to the votes number) – Totem Oct 29 '14 at 23:48
0
vowels = [ 'a','e','i','o','u']
sentence = "Our World is a better place"
count_vow = 0
count_con = 0
for x in sentence:
    if x.isalpha():
        if x.lower() in vowels:
            count_vow += 1
        else:
            count_con += 1
print count_vow,count_con
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

For vowels:

Basic way of doing this is using a for loop and checking each character if they exist in a string, list or other sequence (vowels in this case). I think this is the way you should first learn to do it since it's easiest for beginner to understand.

def how_many_vowels(text):
  vowels = 'aeiou'
  vowel_count = 0
  for char in text:
    if char.lower() in vowels:
      vowel_count += 1
  return vowel_count 

Once you learn more and figure out list comprehensions, you could do it

def how_many_vowels(text):
  vowels = 'aeiou'
  vowels_in_text = [ch for ch in text if ch.lower() in vowels]
  return len(vowels_in_text)

or as @totem wrote, using sum

def how_many_vowels(text):
  vowels = 'aeiou'
  vowel_count = sum(1 for ch in text if ch.lower() in vowels)
  return vowel_count
Hamatti
  • 1,210
  • 10
  • 11