如何將兩個相反的值分割爲一個字符串?例如(
和)
是 「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?"]
如何將兩個相反的值分割爲一個字符串?例如(
和)
是 「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?"]
您可以使用正則表達式的分割:
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?']
你不需要轉義字符類中的'()'。 – kennytm 2010-08-08 20:17:43
使用正則表達式,既()
字符匹配:
import re
re.split('[()]', string)
在這種特殊情況下,聽起來就像將通過空間更有意義,先分割,然後修剪括號。
out = []
for element in "Wouldn't it be (most) beneficial to have (at least) some idea?".split():
out.append(element.strip('()'))
嗯...重讀這個問題,你想保留一些空間,所以也許不是:),但仍然保持在這裏。
我會*喜歡*保留空格。 – 2010-08-08 20:46:48
在Python中,它們通常被稱爲「列表」,而不是數組。還有「口銜」,相當於PHP的關聯數組。 – quantumSoup 2010-08-08 20:19:29
@quantum:謝謝。我知道這個「適當的」術語,但它和Mongo中的'show tables'一樣。 Mongo沒有桌子,但高興地接受它並向你展示所有藏品。 – 2010-08-08 20:21:08
@Josh K:不,調用列表數組是錯誤的。這就像給自行車打電話,因爲他們都有車輪。 – 2010-08-08 20:24:53