Reverse Vowels of a String in Python

Suppose we have a lowercase string. Our task is to reverse the vowels present in the string. So if the string is “hello”, then the string after vowel reversal will be “holle”. For string “programming”, it will be “prigrammong”

To solve this, we will follow these steps −

  • Take the string and make a list of vowels, and store their indices as well
  • reverse the vowel list
  • set idx := 0
  • for i := 0 to length of given string – 1
    • if i is in index list −
      • put vowels[i] into final string
      • idx := idx + 1
    • otherwise put string[i] into final string
  • return the list as a string


Let us see the following implementation to get better understanding −

class Solution:
   def reverseVowels(self, s):
      :type s: str
      :rtype: str
      chars = list(s)
      index = []
      vowels = []
      for i in range(len(chars)):
         if chars[i] in ['a','e','i','o','u']:
      vowels = vowels[::-1]
      final = []
      ind = 0
      for i in range(len(chars)):
      if i in index:
         ind += 1
   str1 = ""
   return str1.join(final)




Published on 16-Jan-2020 10:35:41