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.

Table of contents
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.







You must be logged in to post a comment.