2010-08-08 84 views
2

如何將兩個相反的值分割爲一個字符串?例如()是 「deliminators」 和我有以下字符串:Python中的多重分割

Wouldn't it be (most) beneficial to have (at least) some idea? 

我需要以下輸出(作爲數組)

["Wouldn't it be ", "most", " beneficial to have ", "at least", " some idea?"] 
+0

在Python中,它們通常被稱爲「列表」,而不是數組。還有「口銜」,相當於PHP的關聯數組。 – quantumSoup 2010-08-08 20:19:29

+0

@quantum:謝謝。我知道這個「適當的」術語,但它和Mongo中的'show tables'一樣。 Mongo沒有桌子,但高興地接受它並向你展示所有藏品。 – 2010-08-08 20:21:08

+2

@Josh K:不,調用列表數組是錯誤的。這就像給自行車打電話,因爲他們都有車輪。 – 2010-08-08 20:24:53

回答

13

re.split()

s = "Wouldn't it be (most) beneficial to have (at least) some idea?" 
l = re.split('[()]', s); 
+0

+1不重新發明車輪。 – muhuk 2010-08-08 20:53:52

+0

不錯,簡單:) – 2010-08-08 21:13:41

0

您可以使用正則表達式的分割:

import re 
pattern = re.compile(r'[()]') 
pattern.split("Wouldn't it be (most) beneficial to have (at least) some idea?") 
["Wouldn't it be ", 'most', ' beneficial to have ', 'at least', ' some idea?'] 
+3

你不需要轉義字符類中的'()'。 – kennytm 2010-08-08 20:17:43

0

使用正則表達式,既()字符匹配:

import re 
re.split('[()]', string) 
1

在這種特殊情況下,聽起來就像將通過空間更有意義,先分割,然後修剪括號。

out = [] 
for element in "Wouldn't it be (most) beneficial to have (at least) some idea?".split(): 
    out.append(element.strip('()')) 

嗯...重讀這個問題,你想保留一些空間,所以也許不是:),但仍然保持在這裏。

+0

我會*喜歡*保留空格。 – 2010-08-08 20:46:48