Write a while loop that takes a string and counts the vowels? - python

Write a while loop that takes a string and counts the vowels. Use the string “May the force be with you.” Print the results. (Answer: 8)
Any help with this would be greatly appreciated! I kept coming up with a continuous loop. It has to use a while loop and print the number of vowels (8). Thank you!!
count = 0
vowels = ['a', 'e', 'i', 'o', 'u']
s = "May the force be with you."
while i in s:
if i in vowels:
count += 1
print(count)

The statement:
while i in s:
does not do what you think. Were that while a for, it would iterate over the string one character at a time, and probably work.
However, the expression i in s (which is what that is in a while statement) simply checks if i is one of the things in the s "collection" and gives you true or false. It does not iterate i over the s collection.
If i had been set to something, the while loop would either execute infinitely or never, depending on the value of i. If i is not bound to a value, you'll get a run-time error.
As a solution, you can iterate over the characters in a string with something like (from an actual transcript):
>>> str = "pax"
>>> for ch in str:
... print(ch)
...
p
a
x
The equivalent while version would be:
>>> str = "pax"
>>> idx = 0 # OR: idx, slen = 0, len(str)
>>> while idx < len(str): # while idx < slen:
... print str[idx]
... idx += 1
...
p
a
x
though the for variant is generally considered more Pythonic for this sort of task.
Further, you can detect if a character is one of a set of characters by using in, such as in the following transcript:
>>> str = "pax"
>>> for ch in str:
... if ch in "ABCabc":
... print(f"{ch} is either a, b, or c")
...
a is either a, b, or c
So you should be able to combine that for/while loop and if statement to count the vowels and output it (with print).
Note especially the string I use for vowel checking, it also contains the upper-case vowels. And keep in mind, though your specification may only be to use the Latin-ish vowels, the Unicode world of today would not forgive this oversight. See here for example.

Since it needs to be a while, you can slice off a character at a time and loop until the string is empty. As a quick optimization, True adds as 1 and False as 0, so the interior if can be removed.
vowels = ['a', 'e', 'i', 'o', 'u']
s = "May the force be with you."
count = 0
while s:
count += s[0] in vowels
s = s[1:]
print(count)

I think you could use something like this
phrase = "May the force be with you."
vowels = 0
count = 0
while phrase[count] != ".":
if phrase[count] in 'aeiou':
vowels += 1
count+=1
print(vowels)

Related

Need help for p-language deciphering

I don't know if you're familiar with the P-language or if it's something that's just known in my country. Basically, everytime you come across a vowel in a word, you replace the vowel the same vowel + p + the vowel again.
So 'home' would be 'hopomepe' in the p-language.
Now I'm tasked to decipher the p-language and turn sentences that are written in the p-language back to normal.
p = str(input())
for letter in range(1, len(p)):
if p[letter]=='.':
break
if p[letter-1]==p[letter+1] and p[letter]=='p':
p = p[:letter-1] + p[letter+1:]
print(p)
This is my code so far, it works except I don't know how to make it work for double vowel sounds like 'io' in scorpion (scoporpiopion) for example.
Also when a sentence starts with a vowel, this code doesn't work on that vowel.
For example 'Apan epelepephapant' becomes 'Apan elephant' with my code.
And my code crashes with string index out of bounds when it doesn't end on '.' but it crashes everytime when I don't have that if for the '.' case.
TLDR; How can I get change my code so it works for double vowels and at the start of my sentence.
EDIT: To clarify, like in my example, combination vowels should count as 1 vowel. Scorpion would be Scoporpiopion instead of Scoporpipiopon, boat would be boapoat, boot would be boopoot, ...
You can do it using regular expressions:
import re
def decodePLanguage(p):
return re.subn(r'([aeiou]+)p\1', r'\1', p, flags=re.IGNORECASE)[0]
In [1]: decodePLanguage('Apan epelepephapant')
Out[1]: 'An elephant'
In [2]: decodePLanguage('scoporpiopion')
Out[2]: 'scorpion'
This uses re.subn function to replace all regex matches.
In r'([aeiou]+)p\1', the [aeiou]+ part matches several vowels in a row, and \1 ensures you have the same combination after a p.
Then r'\1' is used to replace the whole match with the first vowel group.
EDIT: working code
def decipher(p):
result = ''
while len(p) > 2:
# first strip out all the consecutive consonants each iteration
idx = 0
while p[idx].lower() not in 'aeiou' and idx < len(p) - 2:
idx += 1
result += p[:idx]
p = p[idx:]
# if there is any string remaining to process, that starts with a vowel
if len(p) > 2:
idx = 0
# scan forward until 'p'
while p[idx].lower() != 'p':
idx += 1
# sanity check
if len(p) < (idx*2 + 1) or p[:idx].lower() != p[idx+1:2*idx+1].lower():
raise ValueError
result += p[:idx]
p = p[2*idx+1:]
result += p
return result
In your example input 'Apan epelepephapant', you compare 'A' == 'a' and get False. It seems you want to compare 'a' == 'a', that is, the str.lower() of each.
It also seems you don't check if the character before the p and after the p is a vowel; that is, if you come across the string hph, as written, your function deciphers it to simply h.
Earlier version of code below:
def decipher(p):
while len(p) > 2:
if p[0].lower() in 'aeiou' and p[0].lower() == p[2].lower() and p[1] == 'p':
result += p[0]
p = p[3:]
else:
result += p[0]
p = p[1:]
result += p
return result
called as e.g.
p = str(input())
print(decipher(p))
Since #Kolmar already gave a regex solution, I'm going to add one without regex
To help think through this, I'm going to first show you my solution to encode a regular string into p-language. In this approach, I group the characters in the string by whether or not they are vowels using itertools.groupby(). This function groups consecutive elements having the same key in the same group.
def p_encode(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
s_groups = [(k, list(v)) for k, v in itertools.groupby(s, lambda c: c.lower() in vowels)]
# For scorpion, this will look like this:
# [(False, ['s', 'c']),
# (True, ['o']),
# (False, ['r', 'p']),
# (True, ['i', 'o']),
# (False, ['n'])]
p_output = []
# Now, we go over each group and do the encoding for the vowels.
for is_vowel_group, group_chars in s_groups:
p_output.extend(group_chars) # Add these chars to the output
if is_vowel_group: # Special treatment for vowel groups
p_output.append("p")
p_output.extend(c.lower() for c in group_chars)
return "".join(p_output)
I added a list comprehension to define s_groups to show you how it works. You can skip the list comprehension and directly iterate for is_vowel_group, group_chars in itertools.groupby(s, lambda c: c.lower() in vowels)
Now, to decode this, we can do something similar in reverse, but this time manually do the grouping because we need to process ps differently when they're in the middle of a vowel group.
I suggest you don't modify the string as you're iterating over it. At best, you'll have written some code that's hard to understand. At worst, you'll have bugs because the loop will try to iterate over more indices than actually exist.
Also, you iterate over 1..len(p), and then try to access p[i+1]. In the last iteration this will throw an IndexError. And because you want repeated vowels to count as a single group, this doesn't work. You're going to have to group the vowels and non-vowels separately, and then join them into a single string.
def p_decode(p):
vowels = {'a', 'e', 'i', 'o', 'u'}
p_groups = []
current_group = None
for c in p:
if current_group is not None:
# If the 'vowelness' of the current group is the same as this character
# or ( the current group is a vowel group
# and the current character is a 'p'
# and the current group doesn't contain a 'p' already )
if (c.lower() in vowels) == current_group[0] or \
( current_group[0] and
c.lower() == 'p' and
'p' not in current_group[1]):
current_group[1].append(c) # Add c to the current group
else:
current_group = None # Reset the current group to None so you can make it later
if current_group is None:
current_group = (c.lower() in vowels, [c]) # Make the current group
p_groups.append(current_group) # Append it to the list
# For scorpion => scoporpiopion
# p_groups looks like this:
# [(False, ['s', 'c']),
# (True, ['o', 'p', 'o']),
# (False, ['r', 'p']),
# (True, ['i', 'o', 'p', 'i', 'o']),
# (False, ['n'])]
p_output = []
for is_vowel_group, group_chars in p_groups:
if is_vowel_group:
h1 = group_chars[:len(group_chars)//2] # First half of the group
h2 = group_chars[-len(group_chars)//2+1:] # Second half of the group, excluding the p
# Add the first half to the output
p_output.extend(h1)
if h1 != h2:
# The second half of this group is not repeated characters
# so something in the input was wrong!
raise ValueError(f"Invalid input '{p}' to p_decode(): vowels before and after 'p' are not the same in group '{''.join(group_chars)}'")
else:
# Add all chars in non-vowel groups to the output
p_output.extend(group_chars)
return "".join(p_output)
And now, we have:
words = ["An elephant", "scorpion", "boat", "boot", "Hello World", "stupid"]
for w in words:
p = p_encode(w)
d = p_decode(p)
print(w, p, d, sep=" | ")
Which gives (prettification mine):
Word
Encoded
Decoded
An elephant
Apan epelepephapant
An elephant
scorpion
scoporpiopion
scorpion
boat
boapoat
boat
boot
boopoot
boot
Hello World
Hepellopo Woporld
Hello World
stupid
stupupipid
stupid
Also, words that aren't actually encoded correctly (such as "stupid") throw a ValueError
>>> p_decode("stupid")
ValueError: Invalid input 'stupid' to p_decode(): vowels before and after 'p' are not the same in group 'upi'

Count how many times a list of characters appear in a string - Python (no count or counter)

I'm a Python newbie, taking a class. I have to find out how many times each letter appears in a string. I've seen all the responses about .count and counter, but this has not been covered yet. I took my string and created a list of the characters so they only appeared once. Then I tried to count how many times the character from the list appears in the string, and I just can't get it to work. I know how to check for a specific letter, but I can't make it check for each letter in my list. Program is below (there are some extra codes, but I'm using them to make sure it's counting properly).
# CONSTANTS and Blank Lists
letter_list = []
count = 0
letter_count = []
index = 0
# Begin programming
my_string = 'SUKI IS SWEET'
for ch in my_string:
if ch not in letter_list:
letter_list.append(ch)
print(letter_list)
print()
for ch in my_string:
if letter_list[index] == ch:
count = count + 1
letter_count.append(count)
# Double-checks to make sure running properly
print(letter_list[0],'appears',letter_count[0], 'times')
print()
print(letter_count)
print()
When I run this, I get the proper answer:
['S', 'U', 'K', 'I', ' ', 'W', 'E', 'T'] (my letter_list)
S appears 3 times (S does appear 3 times)
[3] (my letter_count)
However, I KNOW that my letter_count.append is in the wrong place. But if I move it in, it gets jacked up. And the moment I try to move it along by increasing the index, it blows up (see below):
# CONSTANTS and Blank Lists
letter_list = []
count = 0
letter_count = []
index = 0
# Begin programming
my_string = 'SUKI IS SWEET'
for ch in my_string:
if ch not in letter_list:
letter_list.append(ch)
print(letter_list)
print()
for ch in my_string:
if letter_list[index] == ch:
count = count + 1
letter_count.append(count)
index = index + 1
# Double-checks to make sure running properly
print(letter_list[0],'appears',letter_count[0], 'times')
print()
print(letter_count)
print()
RESULTS:
Traceback (most recent call last):
File "C:\Users\Rogue\Desktop\TEST_2.py", line 30, in
main()
File "C:\Users\Rogue\Desktop\TEST_2.py", line 18, in main
if letter_list[index] == ch:
IndexError: list index out of range
I know I'm messing this up bad. But no matter what I do, I can't seem to get this to work. Please help!
You can use a dictionary:
count = {}
my_string = 'SUKI IS SWEET'
for i in my_string:
if i in count: #check if it exists in dictionary
count[i] += 1
else:
count[i] = 1 #first occurrence of character
print(count)
Output:
{' ': 2, 'E': 2, 'I': 2, 'K': 1, 'S': 3, 'U': 1, 'T': 1, 'W': 1}
The index out of range error comes from the fact that index is a large as your original string (13 chars), but you use it on letter_list, which is a large as the number of unique characters (8 unique chars).
Here's a modified version of your code. It's not efficient, but it works and doesn't require dicts or Counters:
letter_list = []
letter_count = []
# Begin programming
my_string = 'SUKI IS SWEET'
# Create a list of unique characters
for ch in my_string:
if ch not in letter_list:
letter_list.append(ch)
letter_count.append(0)
# Increment values in letter_count
for ch in my_string:
for index in range(len(letter_list)):
if letter_list[index] == ch:
letter_count[index] += 1
# Double-checks to make sure running properly
print(letter_list)
print(letter_count)
for index in range(len(letter_list)):
print("'" + letter_list[index] + "'",'appears',letter_count[index], 'times')
It outputs:
['S', 'U', 'K', 'I', ' ', 'W', 'E', 'T']
[3, 1, 1, 2, 2, 1, 2, 1]
'S' appears 3 times
'U' appears 1 times
'K' appears 1 times
'I' appears 2 times
' ' appears 2 times
'W' appears 1 times
'E' appears 2 times
'T' appears 1 times
There is a very simple way to do this if you are allowed to use Python's built-in sorted function.
We make a sorted list of the characters from the string, and then we scan the list, looking for places where the character changes. When we find a change, the previous group has ended, so we print its character and its count.
At the start of the loop we have a fake group consisting of the empty string, so we need to skip the printing step for that fake group. At the end of the loop we print the info for the last group.
my_string = 'SUKI IS SWEET'
last, count = '', 0
for c in sorted(my_string):
if c != last != '':
print(last, count)
count = 0
last = c
count += 1
print(last, count)
output
2
E 2
I 2
K 1
S 3
T 1
U 1
W 1
The main issue is that index is incrementing much larger than the actual size of letter_list, which is causing your index error. You need to instead make sure that your letter_list and letter_count lists are parallel and the same length, otherwise too many access errors could occur.
Here is another way of writing this code:
def count_frequency(text):
letters = []
freqs = []
ordered_list = sorted(text)
for letter in ordered_list:
if letter not in letters:
letters.append(letter)
freqs.append(1)
else:
letter_loc = letters.index(letter)
freqs[letter_loc] += 1
return letters, freqs
Which uses the same method of having parallel lists keeping track of the letters and their respective frequencies. It sorts the list beforehand using sorted, and returns a tuple containing the letters and frequences.
You can then just print this nicely using zip, which allows you to loop over two same sized lists at once:
letter_freqs = count_frequency('SUKI IS SWEET')
for letter, freq in zip(letter_freqs[0], letter_freqs[1]):
print(letter, "appears", freq, "times")
Output:
appears 2 times
E appears 2 times
I appears 2 times
K appears 1 times
S appears 3 times
T appears 1 times
U appears 1 times
W appears 1 times
You will find that this sort of task is much easier with dictionaries and Counters in the future.
Building on Ajax1234's top voted answer with a bit more information for less advanced programmers.
A python string is an array. Unlike other languages it is not an array of char type values as Python does not have a char data type. A single letter is simply a string of length 1.
So we can access any 'character' in the string the same as we would any array
my_string = "Hello, World!"
print(my_string[0]
print(my_string[1]
print(my_string[2]
Will print
H
e
l
We can also iterate over it as we would any array
for s in my_string:
print(s)
So what you want to do here is
my_dict = {} # create your dict
my_string = "HELLO"
# iterate over your string and add to the count in your dict/map
for s in my_string:
# account for duplicate values!
if s in my_dict:
my_dict[s] += 1
else:
my_dict[s] = 1
print(my_dict)
So if you enter hello as input this will give
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
Since you are counting letters rather than unique characters you may also want to add an if case and use the lower() inbuilt method.

How to append a string to only consonants in a list?

Right now I'm trying to create an oppish translator. That is, after a consonant or several consonants in a row, you add 'op' to those letters. As an example, cow would become copowop or street which would become stropeetop. This is what I have so far:
def oppish(phrase): #with this function I'm going to append 'op' or 'Op' to a string.
consonants = ['b','c','d','f','g','h','i','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowels = ['a', 'e', 'i', 'o', 'u'] #this and the preceding line create a variable for the vowels we will be looking to append 'op' to.
if phrase == '': #error case. if the input is nothing then the program will return False.
return False
phrase_List = list(' ' + phrase) # turns the input phrase into a list which allows for an index to search for consonants later on.
new_phrase_List = list() #creates new list for oppish translation
for i in range(1, len(phrase_List)):
if phrase_List[i] == phrase_List[1]:
new_phrase_List.append(phrase_List[i])
elif phrase_List[i] in consonants:
new_phrase_List.append('op') #adds op to the end of a consonant within the list and then appends it to the newlist
new_phrase_List.append(phrase_List[i]) #if the indexed letter is not a consonant it is appended to the new_phrase_list.
print 'Translation: ' + ''.join(new_phrase_List)
oppish('street')
The only problem here is that the above code yields this
Translation: ssoptopreeopt
I'm not sure what I've done wrong, I've tried going through a visualizer but to no avail. All help is appreciated! :)
This is well suited for itertools.groupby, which will let you group items in an iterable using a key function. The group will accumulate until the return value of the key function changes, at which point group by will yield return value of the key function and an iterator over the accumulated group. In this case, we want our key function to return True if a letter is a vowel. That way, we'll get groups of consecutive consonants, and groups of consecutive vowels back from groupby:
from itertools import groupby
vowels = {'a', 'e', 'i', 'o', 'u'} # set instead of list, because lookups are O(1)
def oppish(phrase):
if not phrase:
return False
out = []
for is_vowel, letters in groupby(phrase, lambda x: x in vowels):
out.append(''.join(list(letters)))
if not is_vowel:
out.append('op')
return ''.join(out)
print oppish('street')
print oppish('cow')
Output:
stropeetop
copowop
I think the problem is in your approach to the problem.
Try to do something like this:
EDIT: Although there's a better (pythonic) answer in this question (thanks to dano), this one does not require additional libraries
vowels = ['a', 'e', 'i', 'o', 'u']
def oppish(word):
result = []
first = True
prev_vowel = False
for letter in list(word):
if (letter in vowels) and (not first) and (not prev_vowel):
result.append('op')
prev_vowel = True
else:
prev_vowel = False
result.append(letter)
first = False
if not prev_vowel:
result.append('op')
print ''.join(result)
oppish('street')
#> stropeetop
TIP: Don't waste your time defining both vowels and consonants. in fact, there are vowels and non-vowels

Replacing a letter with a word

I am wondering how to write a function that replaces a letter with a word without using any built in functions. For example, eyeForI(“William”) returns “Weyelleyeam” which replaces every i with eye.
I know how to do this with a built in function which I already wrote something similar here (though in this case it changes a word with a different word):
def stringChange(s):
for old, new in (
("can't", "can not"),
("shouldn't", "should not"),
("don't", "do not"),
("won't", "will not"),
):
s = s.replace(old, new)
if "!" in s:
s=s.upper()
return s
But I do not know how to write it without using any built in functions.
I know I must use a for loop.
Strings are immutable so you'll want to convert it to a list, make changes, then convert back to a string. For your example,
def eyeForI(word):
word = list(word)
j = 0
while j < len(word):
if word[j] == 'i':
word[j] = 'eye'
j += 1
word = ''.join(word)
return word
If you are just learning the control structures, it's worth mentioning that this can also be accomplished with a for loop instead of a while loop.
def eyeForI(word):
# convert the string word into a list
# word = ['W', 'i', 'l', 'l', 'i', 'a', 'm']
word = list(word)
# loop over indices of the list. len(word) = 7 so i runs from 0-6
for j in xrange(len(word)):
if word[j] == 'i': # if the j'th item in word == "i"
word[j] = 'eye' # change it to "eye"
word = ''.join(word) # join method, explained below
return word
The join method can be confusing at first. It will join all the elements of its argument (in this case word) using the string that calls it as a separator (in this case ''). So we just say, "join the elements of word using an empty string to separate them." Note that you can also build another string from scratch using the + operator and iterating through the original word string if you like (see other answers).
Here's something for you to try and take apart. Rather than a for loop, it involves generators, dictionary with a default argument to get, and join. You can iterate through a string, which means you do not need to convert it into a list first.
s1 = "William"
subs = {'i': 'eye'}
s2 = ''.join(subs.get(c, c) for c in s1)
print(s2)
Here is a solution that does not call anything that would reasonably be called a function or method. It is not very "pythonic" however. It would be difficult to extend due to the hard-coding of the condition, and repeated addition of strings is not preferred.
def eyeForI(word):
result = "" # create an empty string so we can add to it
for c in word: # c will be set to each character in turn
if c == 'i':
result += 'eye' # add the word to the end of result
else:
result += c # add the letter to the end of result
return result
assert eyeForI("William") == "Weyelleyeam" # test it works
I like list comprehensions :)
Why write a whole function if all you need is to perform an specific task which can be done in one line.
You can create a list of the letters:
>>> print [letter if letter is not 'i' else 'eye' for letter in "william" ]
['w', 'eye', 'l', 'l', 'eye', 'a', 'm']
and use the join function to put them together:
>>> print "".join([letter if letter is not 'i' else 'eye' for letter in "william" ])
weyelleyeam

Count vowels from raw input

I have a homework question which asks to read a string through raw input and count how many vowels are in the string. This is what I have so far but I have encountered a problem:
def vowels():
vowels = ["a","e","i","o","u"]
count = 0
string = raw_input ("Enter a string: ")
for i in range(0, len(string)):
if string[i] == vowels[i]:
count = count+1
print count
vowels()
It counts the vowels fine, but due to if string[i] == vowels[i]:, it will only count one vowel once as i keeps increasing in the range. How can I change this code to check the inputted string for vowels without encountering this problem?
in operator
You probably want to use the in operator instead of the == operator - the in operator lets you check to see if a particular item is in a sequence/set.
1 in [1,2,3] # True
1 in [2,3,4] # False
'a' in ['a','e','i','o','u'] # True
'a' in 'aeiou' # Also True
Some other comments:
Sets
The in operator is most efficient when used with a set, which is a data type specifically designed to be quick for "is item X part of this set of items" kind of operations.*
vowels = set(['a','e','i','o','u'])
*dicts are also efficient with in, which checks to see if a key exists in the dict.
Iterating on strings
A string is a sequence type in Python, which means that you don't need to go to all of the effort of getting the length and then using indices - you can just iterate over the string and you'll get each character in turn:
E.g.:
for character in my_string:
if character in vowels:
# ...
Initializing a set with a string
Above, you may have noticed that creating a set with pre-set values (at least in Python 2.x) involves using a list. This is because the set() type constructor takes a sequence of items. You may also notice that in the previous section, I mentioned that strings are sequences in Python - sequences of characters.
What this means is that if you want a set of characters, you can actually just pass a string of those characters to the set() constructor - you don't need to have a list one single-character strings. In other words, the following two lines are equivalent:
set_from_string = set('aeiou')
set_from_list = set(['a','e','i','o','u'])
Neat, huh? :) Do note, however, that this can also bite you if you're trying to make a set of strings, rather than a set of characters. For instance, the following two lines are not the same:
set_with_one_string = set(['cat'])
set_with_three_characters = set('cat')
The former is a set with one element:
'cat' in set_with_one_string # True
'c' in set_with_one_string # False
Whereas the latter is a set with three elements (each one a character):
'c' in set_with_three_characters` # True
'cat' in set_with_three_characters # False
Case sensitivity
Comparing characters is case sensitive. 'a' == 'A' is False, as is 'A' in 'aeiou'. To get around this, you can transform your input to match the case of what you're comparing against:
lowercase_string = input_string.lower()
You can simplify this code:
def vowels():
vowels = 'aeiou'
count = 0
string = raw_input ("Enter a string: ")
for i in string:
if i in vowels:
count += 1
print count
Strings are iterable in Python.
for i in range(0, len(string)):
if string[i] == vowels[i]:
This actually has a subtler problem than only counting each vowel once - it actually only tests if the first letter of the string is exactly a, if the second is exactly e and so on.. until you get past the fifth. It will try to test string[5] == vowels[5] - which gives an error.
You don't want to use i to look into vowels, you want a nested loop with a second index that will make sense for vowels - eg,
for i in range(len(string)):
for j in range(len(vowels)):
if string[i] == vowels[j]:
count += 1
This can be simplified further by realising that, in Python, you very rarely want to iterate over the indexes into a sequence - the for loop knows how to iterate over everything that you can do string[0], string[1] and so on, giving:
for s in string:
for v in vowels:
if s == v:
count += 1
The inner loop can be simplified using the in operation on lists - it does exactly the same thing as this code, but it keeps your code's logic at a higher level (what you want to do vs. how to do it):
for s in string:
if s in vowels:
count += 1
Now, it turns out that Python lets do math with booleans (which is what s in vowels gives you) and ints - True behaves as 1, False as 0, so True + True + False is 2. This leads to a one liner using a generator expression and sum:
sum(s in vowels for s in string)
Which reads as 'for every character in string, count how many are in vowels'.
you can use filter for a one liner
print len(filter(lambda ch:ch.lower() in "aeiou","This is a String"))
Here's a more condensed version using sum with a generator:
def vowels():
string = raw_input("Enter a string: ")
print sum(1 for x in string if x.lower() in 'aeiou')
vowels()
Option on a theme
Mystring = "The lazy DOG jumped Over"
Usestring = ""
count=0
for i in Mystring:
if i.lower() in 'aeiou':
count +=1
Usestring +='^'
else:
Usestring +=' '
print (Mystring+'\n'+Usestring)
print ('Vowels =',count)
The lazy DOG jumped Over
^ ^ ^ ^ ^ ^ ^
Vowels = 7

Categories

Resources