Reputation: 35
I want to count the vowels in a text, this I can do. But I also want to count the amount of vowels followed by a consonant and the amount of vowels followed by a vowel. Can somebody help me with this?
This is what I have so far but it says invalid syntax for the line where I use i+1 in vowels.
s = "text"
vowels = set("aeuio")
consonants = set("qwrtypsdfghjklzxcvbnm")
vowelcount=0
vowelvowelcount=0
consonantcount=0
consvowelcount=0
consconscount=0
vowelconscount=0
for i in s:
if i in vowels:
vowelcount += 1
if i in consonants:
consonantcount +=1
for i in s:
if (i in vowels,and i+1 in vowels):
vowelvowelcount +=1
print ("number of vowels:", vowelcount)
print ("number of consonants:", consonantcount)
print ("number of vowels followed by vowels:", vowelvowelcount)
Upvotes: 1
Views: 117
Reputation: 1077
I like Willem's answer. I have another option. I might want to use enumerate
in this case.
for i, char in enumerate(s[:-1]):
if char in vowels and s[i+1] in vowels:
vowelvowelcount +=1
Upvotes: 1
Reputation: 477160
If you use for i in s
, i
is not an index: it is a character. A quick way to solve this is using:
for i in range(len(s)-1):
if s[i] in vowels and s[i+1] in consonants:
vowelconscount += 1
elif s[i] in vowels and s[i+1] in vowels:
vowelvowelcount += 1
# ...
Here we use range(..)
to iterate over all indices up to (but excluding) len(s)-1
. For each of these indices i
we check if the character in s
at position i
(that is s[i]
) is vowels
and the next character s[i+1]
is a cononant.
Upvotes: 1