Python - Custom Split Comma Separated Words
Last Updated :
22 Mar, 2023
While working with Python, we can have problem in which we need to perform the task of splitting the words of string on spaces. But sometimes, we can have comma separated words, which have comma's joined to words and require to split them separately. Lets discuss certain ways in which this task can be performed.
Method #1 : Using replace()
Using replace() is one way to solve this problem. In this, we just separate the joined comma from string to spaced so that they can be splitted along with other words correctly.
Python3
# Python3 code to demonstrate working of
# Custom Split Comma Separated Words
# Using replace()
# initializing string
test_str = 'geeksforgeeks, is, best, for, geeks'
# printing original string
print("The original string is : " + str(test_str))
# Distance between occurrences
# Using replace()
res = test_str.replace(", ", " , ").split()
# printing result
print("The strings after performing splits : " + str(res))
OutputThe original string is : geeksforgeeks, is, best, for, geeks
The strings after performing splits : ['geeksforgeeks', ',', 'is', ',', 'best', ',', 'for', ',', 'geeks']
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 #2 : Using re.findall()
This problem can also be used using regex. In this, we find the occurrences of non space word and perform a split on that basis.
Python3
# Python3 code to demonstrate working of
# Custom Split Comma Separated Words
# Using re.findall()
import re
# initializing string
test_str = 'geeksforgeeks, is, best, for, geeks'
# printing original string
print("The original string is : " + str(test_str))
# Distance between occurrences
# Using re.findall()
res = re.findall(r'\w+|\S', test_str)
# printing result
print("The strings after performing splits : " + str(res))
OutputThe original string is : geeksforgeeks, is, best, for, geeks
The strings after performing splits : ['geeksforgeeks', ',', 'is', ',', 'best', ',', 'for', ',', 'geeks']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3 - Custom Split Comma Separated Words Using String split() Method.
In this method to achieve the same result is by using the string split() method. we can split the string based on the comma separator, and then strip any whitespace characters from each resulting substring.
Python3
test_str = 'geeksforgeeks, is, best, for, geeks'
# Split the string based on commas and strip whitespace from each substring
res = [s.strip() for s in test_str.split(',')]
# printing result
print("The strings after performing splits : " + str(res))
OutputThe strings after performing splits : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Time complexity: O(n), where n is the length of the input string test_str.
Auxiliary space: O(n), where n is the length of the input string test_str.
Method #4: Using list comprehension
This program splits a string into words using the comma as a delimiter, and then removes any leading or trailing whitespace from each word using a list comprehension. The resulting list of stripped words is then printed.
Python3
test_str = 'geeksforgeeks, is, best, for, geeks'
res = [word.strip() for word in test_str.split(',')]
print(res)
Output['geeksforgeeks', 'is', 'best', 'for', 'geeks']
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 #5: Using the string.split() method
Python3
test_str = 'geeksforgeeks, is, best, for, geeks'
# Split words with list comprehension
res = [word.strip() for word in test_str.split(",")]
# printing result
print("The strings after performing splits : " + str(res))
OutputThe strings after performing splits : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Time complexity: O(n), where n is the length of the input string, test_str.
Auxiliary space: O(n), where n is the length of the input string, test_str.
Method #6: Using the re.split() method from the re module
One additional method for splitting comma-separated words in Python is using the re.split() method from the re module.
Step-by-step approach:
- Import the re module.
- Initialize the string to be split, test_str.
Define a regular expression pattern that matches commas followed by any number of spaces (",\s*"). - Use the re.split() method with the regular expression pattern to split the string.
- Print the resulting list of split strings.
Below is the implementation of the above approach:
Python3
import re
# initializing string
test_str = 'geeksforgeeks, is, best, for, geeks'
# printing original string
print("The original string is : " + str(test_str))
# Custom Split Comma Separated Words Using re.split()
pattern = ",\s*"
res = re.split(pattern, test_str)
# printing result
print("The strings after performing splits : " + str(res))
OutputThe original string is : geeksforgeeks, is, best, for, geeks
The strings after performing splits : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
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. In the best case, where the input string contains only one comma, the space complexity is O(1).
Similar Reads
Input a comma separated string - Python
Handling comma-separated input in Python involves taking user input like '1, 2, 3' and converting it into usable data types such as integers or floats. This is especially useful when dealing with multiple values entered in a single line. Let's explore different efficient methods to achieve this:Usin
3 min read
Python - Sort words separated by Delimiter
Given string of words separated by some delimiter. The task is to sort all the words given in the string Input : test_str = 'gfg:is:best:for:geeks', delim = "*" Output : best*for*geeks*gfg*is Explanation : Words sorted after separated by delim. Input : test_str = 'gfg:is:best', delim = "*" Output :
6 min read
Split a sentence into list of words in Python
When working with text in Python, we often need to break down a sentence into individual words. This task is easy to accomplish in Python using different methods. The simplest way is by using split(), but more complex tasks can be handled with regular expressions or list comprehension. Depending on
2 min read
How to Count Repeated Words in a String in Python
In this article, we will learn how to count repeated words in a string. Python provides several methods to Count Repeated Words , such as dictionaries, collections. Counter module, or even regular expressions. The simplest way to count repeated words is by splitting the string into individual words
2 min read
Python program to count words in a sentence
In this article, we will explore different methods for counting words in a sentence. The split() method is one of the simplest and most efficient ways to count words in a sentence.Pythons = "Python is fun and versatile." # Counting words word_count = len(s.split()) print(word_count) Output5 Explanat
2 min read
Convert List to Delimiter Separated String - Python
The task of converting a list to a delimiter-separated string in Python involves iterating through the list and joining its elements using a specified delimiter. For example, given a list a = [7, "Gfg", 8, "is", "best", 9] and a delimiter "*", the goal is to produce a single string where each elemen
3 min read
Python - Convert Delimiter separated list to Number
Given a String with delimiter separated numbers, concatenate to form integer after removing delimiter. Input : test_str = "1@6@7@8", delim = '@' Output : 1678 Explanation : Joined elements after removing delim "@"Input : test_str = "1!6!7!8", delim = '!' Output : 1678 Explanation : Joined elements a
6 min read
Python | Rear stray character String split
Python3 # Python3 code to demonstrate working of # Rear stray character String split # Using list comprehension # initializing string test_str = 'gfg, is, best, ' # printing original string print("The original string is : " + test_str) # Rear stray character String split # Using list compr
5 min read
Python - Convert delimiter separated Mixed String to valid List
Given a string with elements and delimiters, split elements on delimiter to extract with elements ( including containers). Input : test_str = "6*2*9*[3, 5, 6]*(7, 8)*8*4*10", delim = "*" Output : [6, 2, 9, [3, 5, 6], (7, 8), 8, 4, 10] Explanation : Containers and elements separated using *. Input :
10 min read
Join List With Separator in Python
The task of joining a list with a separator in Python involves combining the elements of the list into a single string, where each element is separated by a specified separator. The separator, such as a comma, can be placed between the elements to create a well-formatted string. For example, given t
3 min read