2013-12-08 32 views
1

我有這樣的字符串:Python的正則表達式re.findall - 將一個字符串分解成兩個

「C BOS - 從皇家失望買賣」

而且我想在衝刺之前,它們分爲一切,之後的一切。因此,在兩個變量名new1和NEW2簡單地說,我想上面的是:

名new1 = 「C BOS」

NEW2 =

我是新來重新使 「從皇家失望買賣」我無法弄清楚如何讓findall工作。以下是我的嘗試:

import re 

myval = "C BOS - Traded from Royal Disappointments" 

new1 = re.findall(r'*\s\s\-', myval) 
new2 = re.findall(r'-\s*', myval) 

我知道這可能不是很接近但我不清楚如何表達。

+4

你可以通過'your_string.split'(' - ')'逃脫嗎? –

回答

2

使用re.split

>>> import re 
>>> s = "C BOS - Traded from Royal Disappointments" 
>>> re.split(r'\s*-\s*', s) 
['C BOS', 'Traded from Royal Disappointments'] 

結果賦給變量:

>>> new1, new2 = re.split(r'\s*-\s*', s) 
>>> new1 
'C BOS' 
>>> new2 
'Traded from Royal Disappointments' 

一個非正則表達式版本,但需要兩個遍:

>>> map(str.strip, s.split('-')) 
['C BOS', 'Traded from Royal Disappointments'] 

如果字符串包含超過1 -,你仍然想只有一次拆分,再經過分計數re.split

>>> s = "C BOS - Traded from Royal Disappointments - foobar" 
>>> re.split(r'\s*-\s*', s, 1) 
['C BOS', 'Traded from Royal Disappointments - foobar'] 
2

我會做到這一點無需重新,只要你的字符串例子也是如此。

旅遊注意:超過一個'-'或沒有'-'

您可能需要辦理分割和分配可能是個例外。

>>> example = "C BOS - Traded from Royal Disappointments" 
>>> before, after = example.split('-') 
>>> before = before.strip() 
>>> after = after.strip() 
>>> print before 
C BOS 
>>> print after 
Traded from Royal Disappointments 
>>> 
相關問題