Split a String by a Delimiter in Python
Below are the possible approaches to split a string by a delimiter in Python:
- Using re.split() method
- Using str.strip() method
- Using csv.reader() method
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’].
Python3
import re data = "Geeks,for,Geeks" result = re.split( ',' , data) print (result) |
['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’].
Python3
data = "Geeks,for,Geeks" result = [substring.strip() for substring in data.split( ',' )] print (result) |
['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’].
Python3
import csv data = "Geeks,for,Geeks" result = list (csv.reader([data]))[ 0 ] print (result) |
['Geeks', 'for', 'Geeks']
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.