The Wayback Machine - https://web.archive.org/web/20240713092452/https://www.geeksforgeeks.org/python-custom-split-comma-separated-words/
Open In App

Python – Custom Split Comma Separated Words

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

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))


Output

The 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))


Output

The 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))


Output

The 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))


Output

The 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))


Output

The 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

How to split a column with comma separated values in PySpark's Dataframe?
In this article, we are going to learn how to split a column with comma-separated values in a data frame in Pyspark using Python. This is a part of data processing in which after the data processing process we have to process raw data for visualization. we may get the data in which a column contains comma-separated data which is difficult to visual
5 min read
Python | Convert key-value pair comma separated string into dictionary
Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task. Method #1: Using dictionary comprehension
5 min read
Python program to input a comma separated string
Given an input string that is comma-separated instead of space. The task is to store this input string in a list or variables. This can be achieved in Python using two ways: Using List comprehension and split()Using map() and split() Method 1: Using List comprehension and split() split() function helps in getting multiple inputs from the user. It b
3 min read
Convert Lists to Comma-Separated Strings in Python
Making a comma-separated string from a list of strings consists of combining the elements of the list into a single string with commas between each element. In this article, we will explore three different approaches to make a comma-separated string from a list of strings in Python. Make Comma-Separated String from List of Strings in PythonBelow ar
2 min read
Convert comma separated string to array in PySpark dataframe
In this article, we will learn how to convert comma-separated string to array in pyspark dataframe. In pyspark SQL, the split() function converts the delimiter separated String to an Array. It is done by splitting the string based on delimiters like spaces, commas, and stack them into an array. This function returns pyspark.sql.Column of type Array
3 min read
Convert Column with Comma Separated List in Spark DataFrame
Spark DataFrames is a distributed collection of data organized into named columns. They are similar to tables in a traditional relational database but can handle large amounts of data more efficiently thanks to their distributed nature. DataFrames can be created from a variety of sources such as structured data files, tables in Hive, external datab
3 min read
How To Break Up A Comma Separated String In Pandas Column
Pandas library is a Python library which is used to perform data manipulation and analysis. It offers various 2D data structures and methods to work with tables. Some times, the entire data can be in the format of string, which needed to be broken down in-order to organize the information in the pandas data structures. In this article, let us under
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 : best*gfg*is Explanation : Words sorted after separ
6 min read
Python | Custom list split
Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed. This is quite a useful utility to have knowledge about. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip() By coupling
8 min read
Python - Split a String by Custom Lengths
Given a String, perform split of strings on the basis of custom lengths. Input : test_str = 'geeksforgeeks', cus_lens = [4, 3, 2, 3, 1] Output : ['geek', 'sfo', 'rg', 'eek', 's'] Explanation : Strings separated by custom lengths.Input : test_str = 'geeksforgeeks', cus_lens = [10, 3] Output : ['geeksforge', 'eks'] Explanation : Strings separated by
2 min read
Practice Tags :
three90RightbarBannerImg