4

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']
3
  • 2
    The comma looks very important here :), but you do not need to escape it Commented Nov 18, 2016 at 11:21
  • See Why are empty strings returned in split() results? for some more on those empty strings. Commented Nov 18, 2016 at 11:22
  • indeed the comma is important (in german) otherwise you eat granny :), Thanks Rad Lexus,i will have look Commented Nov 18, 2016 at 11:25

4 Answers 4

4

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))
Sign up to request clarification or add additional context in comments.

2 Comments

yes that perfectly works! eventhough i dont understand whats the difference in my attempt! Thanks!
The main difference is the use of findall instead of split.
0

This should work for you:

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

1 Comment

it somehow yields: <filter object at 0x000000000514A208>
0

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

2 Comments

your proposal yields: ['We', 'eat', '', 'Granny']
It returns the same output as what you asked for, for me
0

how about

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.