如果我有这条线
"he is a good man and he goes every day to a school"
而且我想检测两个单词“ he”和“之间的含义是什么,所以输出将是
is a good man
我试过了
for line in file:
print line[line.index('he'): line.index('and')]
这段代码给出了输出
he is a good man
我怎样才能做到这一点?
尝试使用以下命令re.search()
:
import re
s = "he is a good man and he goes every day to a school"
result = re.search('he (.*) and', s)
#^-------^ Find string in between 'he' and 'and'
print result.group(1)
输出:
>>>
is a good man
>>>
另外,如果您不喜欢该re
模块,则还有许多其他方法可以执行此操作。
请在这里看看:查找两个子字符串之间的字符串
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句