Creating a Custom Vowel Iterator in Python

Here’s a Python function that iterates a string to find vowels comparing vowels list. It results in a vowel list in the output. It is a helpful example for data analysts.

User defined iterator
Photo by Teona Swift on Pexels.com

Table of contents

  1. Iterating a string: An Example Code
  2. Step-by-step explanation

Iterating a string: An Example Code

Precisely, use init, iter, and next methods in a Class. Here is an explanation.

class VowelIterator:
  def __init__(self, string):
      self.string = string
      self.index = 0
  def __iter__(self):
      return self
  def __next__(self):
      vowels = ['a', 'e', 'i', 'o', 'u']
      while self.index < len(self.string):
          char = self.string[self.index]
          self.index += 1
          if char.lower() in vowels:
              return char
      raise StopIteration


my_string = "Srini Blog"
vowels = VowelIterator(my_string)
for vowel in vowels:
  print(vowel, end=" ")

Output

i i o

Step-by-step explanation

class VowelIterator:
    def __init__(self, string):
        self.string = string
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        vowels = ['a', 'e', 'i', 'o', 'u']

        while self.index < len(self.string):
            char = self.string[self.index]
            self.index += 1

            if char.lower() in vowels:
                return char

        raise StopIteration

Initializes the string in the __init__() method. The __iter__() method initiates iteration. Here, the index variable keeps track of the current position in the string.  

The process in the __next__() method is to iterate each string character. It then compares each character to the vowel list. If a vowel is found, it returns the vowel. And the loop continues. In the end, it raises StopIteration to break the loop.

Discover more from Srinimf

Subscribe now to keep reading and get access to the full archive.

Continue reading