Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 I got now, but I am getting some weird output: (Don't worry, the sentence is translated from German)

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

    >>>['We', ' ', 'eat', ',', '', ' ', 'Granny']

What I actually want to have is:

    >>>['We', ' ', 'eat', ',', ' ', 'Granny']
like image 746
Vincent van Munky Avatar asked Sep 06 '25 23:09

Vincent van Munky


1 Answers

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))
like image 109
Sebastian Proske Avatar answered Sep 09 '25 12:09

Sebastian Proske