code
Python exercise : Find number of vowels in given string
Python exercise
**************Episode: 2
Level: Beginner
If you have any given string like S="Hello World" write Python 3 function which returns number of vowels in that string.
S="Hello World"
Vowels are a, e, i, u, o
function totalVowels(str):
# your code here
Please comment your answer.
You can also, instead of using predefined string, let user type any string. How would you do that?
Expand solution
First solution is to use for loop.
L = ["a","e","i","o","u"]
s = "Hello World"
s = s.lower()
counter = 0
for i in range(len(s)):
if s[i] in L:
counter += 1
print("Your string has "+ str(counter)+" vowels.")
A bit more elegant solution which executes faster is to use list comprehensions.
def totalVowels(str):
vowels=['a','e','i','o','u']
counter=[l for l in str.lower() if l in vowels]
return len(counter)
print("Your string has " + str(totalVowels("Hello World")) + " vowels.")
Thank you.


Post a Comment
0 Comments
Thanks for sharing your thoughts !