2017-02-06 14 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']