Open In App

Python – Split String on vowels

Last Updated : 02 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 that.

Naive approach: 

  • Initialize variable vowels to contain all the vowels.
  • Initialize an empty list result and a variable temp to an empty string.
  • Iterate through each character in the input string test_str.
  • For each character, check if it is a vowel (by checking if it is in the vowels variable).
  • If the character is a vowel and the temp variable is not empty, append temp to the result list and reset temp to an empty string.
  • If the character is not a vowel, add it to the temp variable.
  • After the iteration, if the temp variable is not empty, append it to the result list.
  • Return the result list.

Python3




def split_on_vowels(test_str):
    vowels = 'aeiouAEIOU'
    result = []
    temp = ""
    for char in test_str:
        if char in vowels:
            if temp != "":
                result.append(temp)
                temp = ""
        else:
            temp += char
    if temp != "":
        result.append(temp)
    return result
 
test_str = 'GFGaBstuforigeeks'
print(split_on_vowels(test_str))


Output

['GFG', 'Bst', 'f', 'r', 'g', 'ks']

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 1 : Using regex() + split()

In this, we use regex split() which accepts multiple characters to perform split, passing list of vowels, performs split operation over string.

Python3




# Python3 code to demonstrate working of
# Split String on vowels
# Using split() + regex
import re
 
# initializing strings
test_str = 'GFGaBste4oCS'
 
# printing original string
print("The original string is : " + str(test_str))
 
# splitting on vowels
# constructing vowels list
# and separating using | operator
res = re.split('a|e|i|o|u', test_str)
 
# printing result
print("The splitted string : " + str(res))


Output

The original string is : GFGaBste4oCS
The splitted string : ['GFG', 'Bst', '4', 'CS']

Time Complexity: O(n), where n is the length of the string “test_str”. The “re.split” function splits the string by searching for specified characters (vowels), which takes linear time proportional to the length of the string. 
Auxiliary space: O(1), as it uses a constant amount of memory regardless of the size of the input string “test_str”.

Method 2 : Using replace() and split().

First replace all vowels in string with “*” and then split the string by “*” as delimiter

Python3




# Python3 code to demonstrate working of
# Split String on vowels
 
# initializing strings
test_str = 'GFGaBste4oCS'
 
# printing original string
print("The original string is : " + str(test_str))
 
# splitting on vowels
vow="aeiouAEIOU"
for i in test_str:
    if i in vow:
        test_str=test_str.replace(i,"*")
res=test_str.split("*")
 
# printing result
print("The splitted string : " + str(res))


Output

The original string is : GFGaBste4oCS
The splitted string : ['GFG', 'Bst', '4', 'CS']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Using replace(),split() and ord() methods

Python3




# Python3 code to demonstrate working of
# Split String on vowels
 
# initializing strings
test_str = 'GFGaBste4oCS'
 
# printing original string
print("The original string is : " + str(test_str))
 
# splitting on vowels
x=[97, 101, 105, 111, 117, 65, 69, 73, 79, 85]
for i in test_str:
    if ord(i) in x:
        test_str=test_str.replace(i,"*")
res=test_str.split('*')
# printing result
print("The splitted string : " + str(res))


Output

The original string is : GFGaBste4oCS
The splitted string : ['GFG', 'Bst', '4', 'CS']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4 : Using operator.countOf() method

Python3




import operator as op
 
 
def split_on_vowels(test_str):
    vowels = 'aeiouAEIOU'
    result = []
    temp = ""
    for char in test_str:
        if op.countOf(vowels, char) > 0:
            if temp != "":
                result.append(temp)
                temp = ""
        else:
            temp += char
    if temp != "":
        result.append(temp)
    return result
 
 
test_str = 'GFGaBstuforigeeks'
print(split_on_vowels(test_str))


Output

['GFG', 'Bst', 'f', 'r', 'g', 'ks']

Time Complexity: O(n)
Auxiliary Space: O(n)

 Method5# :using the ‘itertools.groupby ‘function from the ‘itertools’ module

Python3




import itertools
 
# Define the string to be split
test_str = 'GFGaBste4oCS'
 
# Define the vowels to split the string on
vowels = 'aeiouAEIOU'
 
# Print the original string
print("The original string is:", test_str)
 
# Use itertools.groupby to group adjacent characters in test_str based on if they are in vowels
res = [list(g) for k, g in itertools.groupby(test_str, key=lambda x: x not in vowels) if k]
 
# Join each group of characters into a string
res = [''.join(substring) for substring in res]
 
# Print the final split string
print("The split string is:", res)
#this code is contributed by Asif_shaik


Output

The original string is: GFGaBste4oCS
The split string is: ['GFG', 'Bst', '4', 'CS']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #6: Using translate method

Algorithm:

  1. Initialize a string test_str.
  2. Create a translation table that replaces vowels with spaces using the str.maketrans() method.
  3. Apply the translation table to the test_str using the translate() method and store it in a variable named trans_str.
  4. Split the trans_str on spaces and store the result in a list named res.
  5. Print the result.

Python3




# initializing string
test_str = 'GFGaBste4oCS'
 
# create a translation table that replaces vowels with spaces
trans_table = str.maketrans('aeiouAEIOU', ' '*10)
 
# split the string on spaces
res = test_str.translate(trans_table).split()
 
# printing result
print("The splitted string : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The splitted string : ['GFG', 'Bst', '4', 'CS']

Time complexity: The time complexity of this code is O(n) because the maketrans(), translate() and split() methods take linear time.
Auxiliary Space: The space complexity of this code is O(n) because we are creating a new string and a new list to store the results.



Similar Reads

Python | Pandas Split strings into two List/Columns using str.split()
Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string. It works similarly to Python's default split() method but it can only be applied to an individual string. Pandas <code
4 min read
Python | Count and display vowels in a string
In this program, we need to count the number of vowels present in a string and display those vowels. This can be done using various methods. In this article, we will go through few of the popular methods to do this in an efficient manner. Examples: In a simple way Input : Geeks for Geeks Output : 5 ['e', 'e', 'o', 'e', 'e'] This is in a different w
6 min read
Python program to count number of vowels using sets in given string
Given a string, count the number of vowels present in the given string using Sets. You can use sets to count the number of vowels in a given string in Python. Sets are useful to efficiently check for counting the unique occurrences of vowels. Input : GeeksforGeeksOutput : No. of vowels : 5Explaination: The string GeeksforGeeks contains 5 vowels in
4 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 solved. Method #1 : Using loop + join() + zip_longes
7 min read
Python - Replace vowels in a string with a specific character K
Given a string, replace all the vowels with character K. Input : test_str = "Geeks for Geeks"; K='#'Output : "G##ks f#r G##ks" Explanation : All the vowels in test_str are replaced by a given particular character. Input : test_list = "GFG"; K="$"Output : GFGExplanation : As test_str contained no vowel, so the same string is returned. Method #1 : Us
7 min read
Python Program to Count the Number of Vowels in a String
In this article, we will be focusing on how to print each word of a sentence along with the number of vowels in each word using Python. Vowels in the English language are: 'a', 'e', 'i', 'o', 'u'. So our task is to calculate how many vowels are present in each word of a sentence. So let us first design a simple approach that we will be following in
10 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 is a programming concept where a function calls i
3 min read
Python Program to Count Vowels in a String Using Recursion
Given a string, our task is to count the number of vowels in the string using recursion in Python and return the number of vowels. Examples: Input: acbedOutput: 2Input: geeksforgeeksOutput: 5Explanation: We are counting vowels in a string and printing the number of vowels.Python Program to Count Vowels in a String Using RecursionWe can use a recurs
3 min read
Modify the string such that it contains all vowels at least once
Given a string S containing only Uppercase letters, the task is to find the minimum number of replacement of characters needed to get a string with all vowels and if we cannot make the required string then print Impossible. Examples: Input: str = "ABCDEFGHI"Output: AOUDEFGHIExplanation: There are already 3 Vowels present in the string A, E, I we ju
12 min read
Python Program to Accept the Strings Which Contains all Vowels
Given a string, the task is to check if every vowel is present or not. We consider a vowel to be present if it is present in upper case or lower case. i.e. 'a', 'e', 'i'.'o', 'u' or 'A', 'E', 'I', 'O', 'U' . Examples : Input : geeksforgeeksOutput : Not AcceptedAll vowels except 'a','i','u' are not presentInput : ABeeIghiObhkUulOutput : AcceptedAll
6 min read
Practice Tags :
three90RightbarBannerImg