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
from itertools import zip_longest
test_str = "gaeifgsbou"
print ( "The original string is : " + test_str)
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 =' '))
print ( "Alternate consonants vowels are: " + res)
|
Output
The 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
from itertools import zip_longest
test_str = "gaeifgsbou"
print ( "The original string is : " + test_str)
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 = '')))
print ( "Alternate consonants vowels are: " + res)
|
Output
The 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
test_str = "gaeifgsbou"
print ( "The original string is : " + test_str)
vowels = re.findall(r '[aeiou]' , test_str)
consonants = re.findall(r '[^aeiou]' , test_str)
result = ''.join([vowel + consonant for vowel, consonant in zip (vowels, consonants)])
print ( "Alternate consonants vowels are: " + result)
|
Output
The original string is : gaeifgsbou
Alternate consonants vowels are: agefigosub
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using operator.countOf() method
Python3
from itertools import zip_longest
import operator as op
test_str = "gaeifgsbou"
print ( "The original string is : " + test_str)
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 =' '))
print ( "Alternate consonants vowels are: " + res)
|
Output
The 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
test_str = "gaeifgsbou"
print ( "The original string is : " + test_str)
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]
print ( "Alternate consonants vowels are: " + res)
|
Output
The 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
test_str = "gaeifgsbou"
print ( "The original string is : " + test_str)
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))])
print ( "Alternate consonants vowels are: " + res)
|
Output
The 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
test_str = "gaeifgsbou"
print ( "The original string is : " + test_str)
vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ]
consonants =
vowels = [v for v in test_str if v in vowels]
res = ''.join([a + b for a,b in zip (vowels, consonants)])
print ( "Alternate consonants vowels are: " + res)
|
Output
The 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
test_str = "gaeifgsbou"
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)
print ( "Alternate consonants vowels are: " + res)
|
Output
Alternate 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
Test if String Contains Alphabets and Spaces - Python
We are given a string and the task is to determine whether it contains only alphabets and spaces, this is often required when working with datasets where the string must not include any digits, punctuation or special characters. Using all() isspace() and isalpha()This method iterates through each ch
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
We have to reverse the alternate characters in a given string. The task is to identify every second character in the string, reverse their order and keep the other characters unchanged. For example, "abcd" needs to be changed to "cbad" and "abcde" needs to be changed to "ebcda" This can be accomplis
4 min read
Python - Remove all consonants from string
Sometimes, while working with Python, we can have a problem in which we wish to remove all the non vowels from strings. This is quite popular question and solution to it is useful in competitive programming and day-day programming. Lets discuss certain ways in which this task can be performed.Method
7 min read
Python Program to Accept the Strings Which Contains all Vowels
The problem is to determine if a string contains all the vowels: a, e, i, o, u. In this article, weâll look at different ways to solve this. Using all()all() function checks if all vowels are present in the string. It returns True if every condition in the list comprehension is met. [GFGTABS] Python
2 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
How to Create String Array in Python ?
To create a string array in Python, different methods can be used based on the requirement. A list can store multiple strings easily, NumPy arrays offer more features for large-scale data and the array module provides type-restricted storage. Each method helps in managing collections of text values
2 min read