Python split strings by comma
In this post, you will learn how to split strings by comma in Python programming language. In Python, strings are immutable, indexable, and iterable. In the development process, you may come across a situation where you need to split a string by comma. Splitting a string by comma returns a list of the strings between the commas in the first string.
Python string.split() method
Python provides the split() method to split a string into a list. Here is the syntax of the split() method.
string.split(separator, maxsplit)
Here, the separator specifies the separator to use when splitting the string. By default, whitespace is a separator. The maxsplit is a number that specifies how many times the string should be split into a maximum provided number of times. The default value is -1, which is "all occurrences". Both the separator and the maxsplit are optional parameters.
Example1: Python Split String by Comma
In the given Python program, we have taken a string with lumps isolated by commas, split the string, and stored the things in a list.
str = 'Best,platform,to,learn,programming'
str = str.split(',')
print(str)
str1 = 'Success, is, journey'
str1 = str1.split(', ')
print(str1)
Output of the above code-
['Best', 'platform', 'to', 'learn', 'programming']
['Success', 'is', 'journey']
Example2: Python Split String by One or More Commas
If we apply the string.split() method to a string with more than one comma adjacent to each other, we will get empty chunks in return.
str = 'Success,, is,,, journey'
#split string by ,
chunks = str.split(',')
print(chunks)
Output of the above code-
['Success', '', ' is', '', '', ' journey']
But what if we want to return the above chunk in a list without any empty items. We can fix this using the re python package.
import re
str = 'Success,, is,,, journey'
#split string by ,
chunks = re.split(',+', str)
print(chunks)
Output of the above code:
['Success', ' is', ' journey']
Related Articles
Tower of Hanoi Python
Check if two strings are anagrams Python
Convert string to JSON Python
Python program to reverse a string
Permutation of string in Python
Convert a string to a float in Python
Convert string to JSON Python
Remove character from string Python
Python remove punctuation from string
Python multiline string
Count consonants in a string Python
Python heap implementation
zip function in Python
Remove last element from list Python
Convert string to list Python
Remove element from list Python
Python string split multiple delimiters
Python loop through list
Python iterate list with index
Convert string to int Python
Python random choice
Python dict inside list
Python split multiple delimiters
Replace multiple characters Python