How to Split String by Comma in Python?


Python - Split String by Comma

You can split a string in Python with the string formed by the chunks and commas separating them.

In this tutorial, we will learn how to split a string by comma , in Python using String.split().

Examples

1. Split given string by comma

In this example, we will take a string with chunks separated by comma ,, split the string and store the items in a list.

Python Program

str = 'apple,orange,grape'

#split string by ,
chunks = str.split(',')

print(chunks)

Output

['apple', 'orange', 'grape']

2. Split given string by one or more commas

If you use String.split() on String with more than one comma coming adjacent to each other, you would get empty chunks. An example is shown below.

Python Program

str = 'apple,,orange,,,grape'

#split string by ,
chunks = str.split(',')

print(chunks)

Output

['apple', '', 'orange', '', '', 'grape']

In this example, we will take a string with chunks separated by one or more underscore characters, split the string and store the chunk in a list, without any empty items.

We shall use re python package in the following program. re.split(regular_expression, string) returns list of items split from string based on the regular_expression.

Python Program

import re

str = 'apple,,orange,,,grape'

#split string by ,
chunks = re.split(',+', str)

print(chunks)

Regular Expression ,+ represents one or more commas. So, one or more commas is considered as a delimiter.

Output

['apple', 'orange', 'grape']

One ore more adjacent commas is considered as a single delimiter.

Summary

In this tutorial of Python Examples, we learned how to split a string by comma using String.split() and re.split() methods.