How to split a string by string in Python?

Posted on In Tutorial

How to split a string by string in Python? For example,

"a string   separated by space" =>
["a", "string", "separated", "by", "space"]

and

"a,string,separated,by,comma" =>
["a", "string", "separated", "by", "comma"]

Python’s string.split() standard library function, if provided a separator, will split the string by the separator, for example

>>> str2 = "a,string,separated,by,,,comma"
>>> str2.split(",")
['a', 'string', 'separated', 'by', '', '', 'comma']

The remaining problem is to handle the empty strings caused by the consecutive separators. We can filter away the empty strings to solve this.

[s for s in str2.split(",") if s != ""]

or

list(filter(lambda s: s != "", str2.split(",")))

Then we get

['a', 'string', 'separated', 'by', 'comma']