Vincent van Munky
Vincent van Munky

Reputation: 61

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']

Upvotes: 4

Views: 12360

Answers (4)

user5417363
user5417363

Reputation: 101

how about

import re
sentence = "We eat, Granny"
re.split(r'[\s,]+', sentence)

Upvotes: 0

Vaulstein
Vaulstein

Reputation: 22051

Alternate way:

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

Output:

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

Works with both python 2.7 and 3enter image description here

Upvotes: 0

zipa
zipa

Reputation: 27869

This should work for you:

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

Upvotes: 0

Sebastian Proske
Sebastian Proske

Reputation: 8413

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))

Upvotes: 4

Related Questions