2013-01-14 36 views
0

我想分割一個由分號,空格和逗號組合分隔的字符串。例如:如何根據分號,空格和逗號的任意組合拆分python中的字符串?

輸入:"Jan,Feb;Mar Apr, May;"

輸出:["Jan","Feb","Mar","Apr","May"]

因爲split()方法將匹配正是你在它指定什麼,這不是我所需要的,我不能簡單地用這裏split()方法。有人可以幫我弄這個嗎?

+0

好像你要http://docs.python.org/2/library/re.html#re.split。 –

+0

使用帶有適當正則表達式的're.split()'。 – LSerni

+1

報價怎麼樣? –

回答

7

使用re.split

>>> [s for s in re.split(r'[ ,;]', '"Jan","Feb";"Mar" "Apr", "May";') if s] 
['"Jan"', '"Feb"', '"Mar"', '"Apr"', '"May"'] 

if s過濾掉空字符串。

0

嘗試了這一點:

import re 

c = b'"Jan","Feb";"Mar" "Apr", "May"'; 
needle = r'("[^, ;]*")' 
r = re.compile(needle) 

months = r.findall(c) 
print months 
3

re.findall看起來好這裏:

In [168]: strs='"Jan","Feb";"Mar" "Apr", "May";' 

In [169]: import re 

In [170]: re.findall(r'\w+',strs) 
Out[170]: ['Jan', 'Feb', 'Mar', 'Apr', 'May'] 
2

一般來說,正確的答案是正則表達式,但它發生,你可以解決這個特定的問題與方法splitreplace

>>> s = "one two,three;four" 
>>> s.replace(',',' ').replace(';',' ').split() 
['one', 'two', 'three', 'four'] 

我認爲Ashwini's solution是最好的 - 而不是嘗試刪除所有分離的粗俗,只是搜索有用的內容。

+0

Upvoted提到正則表達式,但提供輕量級字符串替換/拆分解決方案。 –

1

也有使用str.translate跟着一個優雅的非正則表達式的解決方案通過str.split

>>> in_str = '"Jan","Feb";"Mar" "Apr", "May";' 
>>> in_str.translate(None,",; ")[1:-1].split("\"\"") 
['Jan', 'Feb', 'Mar', 'Apr', 'May'] 
相關問題