Skip to content Skip to sidebar Skip to footer

How To Split At Spaces And Commas In Python?

I've been looking around here, but I didn't find anything that was close to my problem. I'm using Python3. I want to split a string at every whitespace and at commas. Here is what

Solution 1:

I'd go for findall instead of split and just match all the desired contents, like

import re
sentence = "We eat, Granny"print(re.findall(r'\s|,|[^,\s]+', sentence))

Solution 2:

Alternate way:

split = [a for a in re.split(r'(\s|\,)', sentence.strip()) if a]

Solution 3:

This should work for you:

import re
 sentence = "We eat, Granny" 
 split = list(filter(None, re.split(r'(\s|\,)', sentence.strip())))
 print (split)

Post a Comment for "How To Split At Spaces And Commas In Python?"