2017-02-06 22 views
0

我有以下字符串:Python的更換有一定的可變部分子

Billy got score of 2 and Tommy got score of 3 

我想拆就score of <some number>讓我得到

["Billy got","Tommy got"] 

我怎樣才能在Python做這種分裂?我試過

input.split("score of \d") 

但這不起作用。但是,如果我做

input.split("score of") 

然後我得到

["Billy got "," 2 and Tommy got "," 3"] 

更新:

感謝您的回答原來的崗位。我有一個後續。

如果我想用score of 2$替換score of 2怎麼辦?這意味着每當我看到score of <some number>只是後面加一個字符$

+4

參見['re.split'(https://docs.python.org/3/library/re.html#re.split)如果你想與分裂一個正則表達式。 – khelwood

回答

2

你需要使用上的數字re.split和分割前串旁邊:

>>> import re 
>>> s = "Billy got score of 2 and Tommy got score of 3" 
>>> re.split(r' score of \d+', s) 
['Billy got', ' and Tommy got', ''] 

你也可以做一些清理了列表理解:

>>> [i.strip() for i in re.split(r' score of \d+', s) if i] 
['Billy got', 'and Tommy got'] 
3

那麼爲什麼這不工作的原因是因爲str.split需要字符串的模式:這是不解釋中eted作爲正則表達式

但是,您可以使用re.split

import re 

result = re.split(r'score of \d+(?: and)?',input) 

您還應該添加可選的(?: and)?刪除and組合子。此外,這個答案使用\d+(與+),使得多位數的分數也正確解析(如"Tommy got score of 23")。

在解釋:

$ python3 
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> input="Billy got score of 2 and Tommy got score of 3" 
>>> import re 
>>> re.split(r'score of \d+(?:\s*and\s*)?',input) 
['Billy got ', 'Tommy got ', ''] 
+0

你可能想要'[和]?(方括號),對不對? – MSeifert

+0

@ MSeifert:但'[]'是一個字符組,不是可選模式。 –

+0

在一段時間內沒有使用過正則表達式,但'(和)'應該在單獨的子字符串中匹配'和'。你需要使它成爲模式的一部分,比如'[(and)]'(這是否工作?) – MSeifert

1

正則表達式的說明這裏使用score of(.+?) score of [0-9]+

  • 匹配任何與score of其次是一些數字
  • (.+?)提取任何東西與非貪婪搜索

下面是代碼:

>>> import re 
>>> sentence 
'Billy got score of 2 and Tommy got score of 3' 
>>> sentence.replace(' and ', ' ') 
'Billy got score of 2 Tommy got score of 3' 
>>> results = re.findall('(.+?) score of [0-9]+', sentence.replace(' and ', ' ')) 
>>> print results 
['Billy got', ' Tommy got']