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>只是在数字后添加一个字符$

这不起作用的原因是str.split期望字符串作为模式:它不被解释为正则表达式

但是,您可以使用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*ands*)?',input)
['Billy got ', 'Tommy got ', '']

您需要使用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']

这里使用的正则表达式的解释(.+?) score of [0-9]+

  • 匹配任何内容,后跟一些数字score of
  • (.+?)使用非贪婪搜索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']

最新更新