我正在寻找一种方法来提取字符串的一部分(我认为它们被称为子串)。我一直在寻找解决方案,但还没有找到。这里有一个例子:`
text = input('Insert Math Problem: ')
'''Insert substring recognition script here'''
if text contains('3') and text contains('4'):
print('Contains three and four!')
else:
print('Does not contain three and four.')`
例如,如果我键入What is 3 * 4
,如何才能只获得3 * 4
部分?我想要提取的子字符串的类型是运算和它周围的两个数字。我也希望它是灵活的,它可以找到3*4或3乘以4。我的Python版本是3.6.4,我使用的是Mac。
发布于 2018-02-03 12:35:01
这是你想要的工作方式。这将使用re模块从文本中提取涉及数字和数学运算符(+,/,*,-)的子串。
import re
text = 'foo 3 * 4 - 5 / 6 + 7 foo'
regex = r'\d+|[+/*-]'
elem = re.findall(regex, text)
result = ' '.join(i for i in elem)
print(result)
输出:
3 * 4 - 5 / 6 + 7
发布于 2018-02-03 10:29:27
有许多方法可以实现这一点,一种方法是使用re模块来识别第一个数字(\d
),然后捕获余数(*
)作为子字符串:
import re
substring = re.sub('^[^\d]*', '', text)
print substring
输出:
3 * 4
https://stackoverflow.com/questions/48593142
复制相似问题