-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);
1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

If this solution solved your issue, please consider accepting it as the official answer(the tick mark next to the votes number)
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

2 Comments

You have a type on line 8, should be count_vow += 1
ahh sorry it was a typing mistake
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

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.