Python | Vowel indices in String
Last Updated :
30 Mar, 2023
Sometimes, while working with Python Strings, we can have a problem in which we need to extract indices of vowels in it. This kind of application is common in day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is one way in which this task can be performed. In this we use brute force to perform this task. In this we iterate for each string element and test for vowel.
Python3
# Python3 code to demonstrate working of
# Vowel indices in String
# Using loop
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Vowel indices in String
# Using loop
res = []
for ele in range(len(test_str)):
if test_str[ele] in "aeiou":
res.append(ele)
# printing result
print("The vowel indices are : " + str(res))
Output : The original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #2 : Using enumerate() + list comprehension The combination of above methods can also be used to perform this task. In this, we access the index using enumerate() and list comprehension is used to check for vowels.
Python3
# Python3 code to demonstrate working of
# Vowel indices in String
# Using list comprehension + enumerate()
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Vowel indices in String
# Using list comprehension + enumerate()
res = [idx for idx, ele in enumerate(test_str) if ele in "aeiou"]
# printing result
print("The vowel indices are : " + str(res))
Output : The original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using ord() method
Python3
# Python3 code to demonstrate working of
# Vowel indices in String
# Using loop
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Vowel indices in String
# Using loop
res = []
vow=[97,101,105,111,117]
for ele in range(len(test_str)):
if ord(test_str[ele]) in vow:
res.append(ele)
# printing result
print("The vowel indices are : " + str(res))
OutputThe original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #4 : Using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Vowel indices in String
import operator as op
vowels = "aeiou"
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Vowel indices in String
# Using loop
res = []
for ele in range(len(test_str)):
if op.countOf(vowels, test_str[ele]) > 0:
res.append(ele)
# printing result
print("The vowel indices are : " + str(res))
OutputThe original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#5: Using Recursive method.
Python3
# Python3 code to demonstrate working of
# Vowel indices in String
# Using recursive method
def vowel_indices(string, idx=0, result=None):
if result is None:
result = []
if idx == len(string):
return result
if string[idx] in "aeiou":
result.append(idx)
return vowel_indices(string, idx + 1, result)
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
res=vowel_indices(test_str)
# printing result
print("The vowel indices are : " + str(res))
#this code contributed by tvsk
OutputThe original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]
Time Complexity: O(n)
Space Complexity: O(n)
Method #6 : Using Regex
Python3
# Python3 code to demonstrate working of
# Vowel indices in String
# Using regex
import re
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Vowel indices in String
# Using regex
vowel_regex = re.compile("[aeiou]")
res = [i.start() for i in vowel_regex.finditer(test_str)]
# printing result
print("The vowel indices are : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]
Time Complexity: O(n) where n is the length of the string
Auxiliary Space: O(1)
Explanation: In this method, we use the re.compile method to compile a regular expression pattern "[aeiou]" which matches the vowels in the string. The re.finditer method returns an iterator yielding match objects for all non-overlapping matches. The start method of each match object returns the starting position of the match. The result of the code is the list of starting positions of all the matches of vowels in the string.
Method #7 : Using Filter() and lambda():
Python3
# Initialize the string
test_str = "geeksforgeeks"
# Specify the vowels
vowels = "aeiou"
# printing original string
print("The original string is : " + test_str)
# Find the indices of vowels using filter() function and lambda function
result = list(filter(lambda x: test_str[x] in vowels, range(len(test_str))))
# Print the result
print("The vowel indices are : " + str(result))
#This code is contributed by Jyothi pinjala
OutputThe original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #8 : Using numpy:
Algorithm:
- Create a string 'test_str' and initialize it with some value.
- Convert the string 'test_str' to a list of characters using the built-in list() function.
- Create a numpy array using the converted list of characters.
- Create another numpy array using the list of vowels in the order 'aeiou'.
- Use the built-in np.isin() function to create a Boolean array indicating whether each character in the 'test_str' array is in the 'aeiou' array.
- Use the built-in np.where() function to get the indices of the True values in the Boolean array returned in step 5.
- Access the first array of the tuple returned in step 6 using index 0 and convert it to a list.
- Print the list of vowel indices.
Python3
import numpy as np
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
vowel_indices = np.where(np.isin(np.array(list(test_str)), np.array(list("aeiou")))) # returns a tuple of arrays
vowel_indices = vowel_indices[0].tolist() # get the first array and convert to list
# printing result
print("The vowel indices are : " + str(vowel_indices))
#This code is contributed by Rayudu.
Output:
The original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]
Time Complexity: O(n), where n is the length of the input string 'test_str'. The time complexity is dominated by the np.isin() function, which has a time complexity of O(n).
Auxiliary Space: O(n), where n is the length of the input string 'test_str'. The space complexity is dominated by the two numpy arrays created in steps 3 and 4, each of which has a size of n. The remaining space used by the algorithm is constant.
Similar Reads
Python - Split String on vowels Given a String, perform split on vowels. Example: Input : test_str = 'GFGaBst' Output : ['GFG', 'Bst'] Explanation : a is vowel and split happens on that. Input : test_str = 'GFGaBstuforigeeks' Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']Explanation : a, e, o, u, i are vowels and split happens on th
5 min read
Python | Alternate vowels and consonants in String Sometimes, while working with Strings in Python, we can have a problem in which we may need restructure a string, adding alternate vowels and consonants in it. This is a popular school-level problem and having solution to this can be useful. Let's discuss certain ways in which this problem can be so
7 min read
Recursively Count Vowels From a String in Python Python is a versatile and powerful programming language that provides various methods to manipulate strings. Counting the number of vowels in a string is a common task in text processing. In this article, we will explore how to count vowels from a string in Python using a recursive method. Recursion
3 min read
Character Indices Mapping in String List - Python We are given a string list we need to map characters to their indices. For example, a = ["hello", "world"] so that output should be [[('h', 0), ('e', 1), ('l', 2), ('l', 3), ('o', 4)], [('w', 0), ('o', 1), ('r', 2), ('l', 3), ('d', 4)]].Using a nested for loopA nested for loop iterates through each
3 min read
Python program to check if given string is vowel Palindrome Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzu
5 min read