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 Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read