Python | Alternate vowels and consonants in String
Last Updated :
14 Apr, 2023
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 solved.
Method #1 : Using loop + join() + zip_longest()
The combination of above functions can be used to perform this task. In this, we first, separate vowels and consonants in separate lists. And then join alternatively using zip_longest() and join().
Python3
# Python3 code to demonstrate working of
# Alternate vowels and consonants in String
# using zip_longest() + join() + loop
from itertools import zip_longest
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using zip_longest() + join() + loop
vowels = ['a', 'e', 'i', 'o', 'u']
test_vow = []
test_con = []
for ele in test_str:
if ele in vowels:
test_vow.append(ele)
elif ele not in vowels:
test_con.append(ele)
res = ''.join(''.join(ele) for ele in zip_longest(test_vow, test_con, fillvalue =''))
# printing result
print("Alternate consonants vowels are: " + res)
OutputThe original string is : gaeifgsbou
Alternate consonants vowels are: agefigosub
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using loop + map() + lambda
This task can also be performed using combination of above functionalities. It is similar as above method, the only differences are usage of map() and lambda functions to perform alternate joining.
Python3
# Python3 code to demonstrate working of
# Alternate vowels and consonants in String
# using loop + map() + lambda
from itertools import zip_longest
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using loop + map() + lambda
vowels = ['a', 'e', 'i', 'o', 'u']
test_vow = []
test_con = []
for ele in test_str:
if ele in vowels:
test_vow.append(ele)
elif ele not in vowels:
test_con.append(ele)
res = ''.join(map(lambda sub: sub[0] + sub[1],
zip_longest(test_vow, test_con, fillvalue ='')))
# printing result
print("Alternate consonants vowels are: " + res)
OutputThe original string is : gaeifgsbou
Alternate consonants vowels are: agefigosub
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using regular expression:
Python3
import re
# Initializing string
test_str = "gaeifgsbou"
#printing original string
print("The original string is : " + test_str)
# Find all vowels and consonants using regular expressions
vowels = re.findall(r'[aeiou]', test_str)
consonants = re.findall(r'[^aeiou]', test_str)
# Zip the lists together and join the result
result = ''.join([vowel + consonant for vowel, consonant in zip(vowels, consonants)])
# printing result
print("Alternate consonants vowels are: " + result)
#this code contributed by tvsk
OutputThe original string is : gaeifgsbou
Alternate consonants vowels are: agefigosub
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Alternate vowels and consonants in String
# using operator.countOf() method
from itertools import zip_longest
import operator as op
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using operator.countOf() method
vowels = 'aeiouAEIOU'
test_vow = []
test_con = []
for ele in test_str:
if op.countOf(vowels,ele)>0:
test_vow.append(ele)
elif ele not in vowels:
test_con.append(ele)
res = ''.join(''.join(ele) for ele in zip_longest(test_vow, test_con, fillvalue =''))
# printing result
print("Alternate consonants vowels are: " + res)
OutputThe original string is : gaeifgsbou
Alternate consonants vowels are: agefigosub
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: using for loop and list comprehension
Python3
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using two for loops
vowels = ['a', 'e', 'i', 'o', 'u']
vowels_list = [char for char in test_str if char in vowels]
consonants_list = [char for char in test_str if char not in vowels]
res = ''
for i in range(len(vowels_list)):
res += vowels_list[i]
if i < len(consonants_list):
res += consonants_list[i]
# printing result
print("Alternate consonants vowels are: " + res)
#This code is contributed by Vinay Pinjala.
OutputThe original string is : gaeifgsbou
Alternate consonants vowels are: agefigosub
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using list comprehensions and slicing
Use list comprehensions and slicing to achieve the same result.
Step-by-step approach:
- Initialize two lists, one for vowels and one for consonants.
- Use list comprehension to filter vowels and consonants from the string.
- Use slicing to alternate vowels and consonants.
- Use join() to combine the alternated string.
- Return the alternated string.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Alternate vowels and consonants in String
# using list comprehension and slicing
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using list comprehension and slicing
vowels = ['a', 'e', 'i', 'o', 'u']
test_vow = [ele for ele in test_str if ele in vowels]
test_con = [ele for ele in test_str if ele not in vowels]
res = ''.join([test_vow[i//2] if i%2==0 else test_con[i//2] for i in range(len(test_str))])
# printing result
print("Alternate consonants vowels are: " + res)
OutputThe original string is : gaeifgsbou
Alternate consonants vowels are: agefigosub
Time complexity: O(n)
Auxiliary space: O(n)
Method #7: Using list comprehension and zip()
Use list comprehension and the built-in zip() function to iterate over pairs of consonants and vowels in the string
- initializing string
- printing original string
- Alternate vowels and consonants in String using list comprehension and zip()
- printing result
Python3
# Python3 code to demonstrate working of
# Alternate vowels and consonants in String
# using list comprehension and zip()
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using list comprehension and zip()
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [c for c in test_str if c not in vowels]
vowels = [v for v in test_str if v in vowels]
res = ''.join([a+b for a,b in zip(vowels, consonants)])
# printing result
print("Alternate consonants vowels are: " + res)
OutputThe original string is : gaeifgsbou
Alternate consonants vowels are: agefigosub
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.
Method #8: Using heapq:
Algorithm:
- Initialize vowels_list as empty list and consonants_list as empty list
- For each character ch in test_str, if ch is a vowel, append it to vowels_list, else append it to consonants_list.
- Sort the vowels_list and consonants_list using heapq.heappush() and heapq.heappop().
- Initialize an empty string res.
- For i in range(min(len(vowels_list), len(consonants_list))), append the popped element from vowels_list and consonants_list alternatively to res.
- Append the remaining elements of vowels_list and consonants_list to res.
- Print the final res string.
Python3
import heapq
# initializing string
test_str = "gaeifgsbou"
# Alternate vowels and consonants in String
# using heapq
vowels = ['a', 'e', 'i', 'o', 'u']
vowels_list = [ch for ch in test_str if ch in vowels]
consonants_list = [ch for ch in test_str if ch not in vowels]
res = ''.join([heapq.heappop(consonants_list) + heapq.heappop(vowels_list) for i in range(min(len(vowels_list), len(consonants_list)))])
res += ''.join(consonants_list) + ''.join(vowels_list)
# printing result
print("Alternate consonants vowels are: " + res)
#This code is contributed by Rayudu.
OutputAlternate consonants vowels are: gabefigosu
Time Complexity:
The time complexity of the algorithm is O(nlogn), where n is the length of the input string test_str. This is because the sorting operation in step 3 takes O(nlogn) time.
Space Complexity:
The space complexity of the algorithm is O(n), where n is the length of the input string test_str. This is because we are storing the vowels_list and consonants_list lists which can have a maximum length of n. Additionally, the res string can also have a maximum length of n.
Similar Reads
Python - Alternate Strings Concatenation The problem of getting the concatenation of a list is quite generic and we might someday face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing the concatenation of alternate elements. Letâs discuss certain ways in which this can be performed. Met
3 min read
Alternate cases in String - Python The task of alternating the case of characters in a string in Python involves iterating through the string and conditionally modifying the case of each character based on its position. For example, given a string s = "geeksforgeeks", the goal is to change characters at even indices to uppercase and
3 min read
Python - Replace Consonants by i, Vowels by j Given a String, perform the replacement of all the vowels with i, and all the consonants using j. Input : test_str = 'geeksforgeeks', i, j = "A", "B" Output : BAABBBABBAABB Explanation : All vowels replaced by A and consonants by B. Input : test_str = 'gfg', i, j = "A", "B" Output : BBB Explanation
5 min read
Python | Vowel indices in String 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
6 min read
Reverse Alternate Characters in a String - Python Reversing alternate characters in a string involves rearranging the characters so that every second character is reversed while maintaining the original order of other characters. For example, given the string 'abcde', reversing the alternate characters results in 'ebcda', where the first, third and
3 min read