Problem: Write a python program to find the last occurrence of a character in a given string. In this case, the character will be a vowel.
Example
Input: "You are awesome"
Output: "Index of the last occurrence of the vowel is 14"
Solution
Iterate through the given string and check if each character is a vowel or not. When a vowel appears, update the index variable according to the index of that vowel or character.
Code
def checkVowel(ch):
# returns true if the character is found in the list
return ch.lower() in ['a', 'e', 'i', 'o', 'u']
def countVowel(string):
index = -1
for i in range(len(string)):
if checkVowel(string[i]):
# updating index variable
index = i
return index
if __name__ == "__main__":
string = "You are beautiful"
status = countVowel(string)
if status != -1:
print("Index of the last occurrence vowel is: ", status)
else:
print("Sorry! No vowel found")
Output
Index of the last occurrence vowel is: 15
Exercise
☛Find the last occurrence of a consonant in a given string using python