2016-11-18 31 views
0

我一直在這裏找,但沒有發現任何接近我的問題。我使用python3。 我想分割每個空格和逗號的字符串。以下是我現在得到的,但我得到一些奇怪的輸出: (不擔心這句話的德國翻譯)如何在Python中的空格和逗號分割?

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

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

什麼其實我是想擁有的是:

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

逗號看上去非常重要的在這裏:),但你不需要逃避它 –

+0

參見[爲什麼是空的字符串在split()結果中返回?](http://stackoverflow.com/q/2197451/2564301)瞭解更多關於這些空字符串的信息。 – usr2564301

+0

確實逗號是重要的(在德國)否則你吃奶奶:),謝謝雷克薩斯,我會看看 –

回答

1

另一種方法:

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

你的建議產量:['我們','吃','','奶奶'] –

+0

編輯答案 – Vaulstein

0

這應該爲你工作:

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

它不知何故產生: <在0x000000000514A208過濾器對象> –

+0

是的,我用2.7測試。做了一個編輯。 – zipa

1

我會去的findall而不是分裂,只是符合所有需要的內容,像

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

是的,這是完美的作品!儘管我不明白我的嘗試有什麼區別!謝謝! –

+0

主要區別在於使用'findall'而不是'split'。 –