Open In App

Split a String by a Delimiter in Python

In Python Programming, the split() method is used to split a string into a list of substrings which is based on the specified delimiter. This method takes the delimiter as an argument and returns the list of substrings. Along with this method, we can use various approaches wot split a string by the specified delimiter in Python. In this article, we will explore different approaches to split a string by a delimiter in Python.

Split a String by a Delimiter in Python

Below are the possible approaches to split a string by a delimiter in Python:



Split a String by a Delimiter Using re.split() method

The below approach code uses re.split() method in Python, with the regular expression ‘,’, used to split the string “Geeks,for,Geeks” at each comma, resulting in the list [‘Geeks’, ‘for’, ‘Geeks’].




import re
data = "Geeks,for,Geeks"
result = re.split(',', data)
print(result)

Output

['Geeks', 'for', 'Geeks']


Split a String by a Delimiter Using the str.strip() method

The below approach code uses split(‘,’) to break the string “Geeks,for,Geeks” into substrings at each comma, and then applies strip() to remove leading and trailing whitespaces, producing the list [‘Geeks’, ‘for’, ‘Geeks’].




data = "Geeks,for,Geeks"
result = [substring.strip() for substring in data.split(',')]
print(result)

Output
['Geeks', 'for', 'Geeks']


Split a String by a Delimiter Using csv.reader() method

The below approach code uses csv.reader([data]) to interpret the string “Geeks,for,Geeks” as a CSV row, and list(…)[0] extracts the resulting list, printing [‘Geeks’, ‘for’, ‘Geeks’].




import csv
data = "Geeks,for,Geeks"
result = list(csv.reader([data]))[0]
print(result)

Output
['Geeks', 'for', 'Geeks']


Conclusion

In conclusion, the split() method in Python is a function for splitting strings into substrings based on a specified delimiter. The above approaches, including re.split(), str.strip(), and csv.reader(), offer similar functionality to split() function. These techniques help developers to efficiently manipulate and extract meaningful information from strings using various delimiter-based splitting methods in Python.


Article Tags :