Python 获取包含起始和结束的部分字符串
我试图从带有开始和结束字符串的字符串中提取日期 例如:Python 获取包含起始和结束的部分字符串,python,string,function,dataframe,substring,Python,String,Function,Dataframe,Substring,我试图从带有开始和结束字符串的字符串中提取日期 例如: comment = " text text text due on: 12/31/2015. REVIEWER'S COMMENTS: APPROVED. text text text" start = "due on:" end = "." 我希望返回从到期日到到期日之后的第一个期间(即12/31/2015 相反,我的代码返回: >>> print(comment1.partition(start)[-1].r
comment = " text text text due on: 12/31/2015. REVIEWER'S COMMENTS: APPROVED. text text text"
start = "due on:"
end = "."
我希望返回从到期日到到期日之后的第一个期间(即12/31/2015
相反,我的代码返回:
>>> print(comment1.partition(start)[-1].rpartition(end)[0])
12/31/2015. REVIEWER'S COMMENTS: APPROVED
似乎我的代码返回了从开始到“批准”之后的期间之间的所有内容,但我希望它在日期之后的期间结束 从文档中:
:在最后一次出现sep时拆分字符串
由于您的end=“.”
在批准后最后一次出现。
,因此此位置用于拆分
您希望第一次出现在到期日之后:
,因此,在第一次拆分的剩余部分,另一次出现在:
>>> comment.partition(start)[-1].partition(end)[0].strip()
'12/31/2015'
您不需要rpartition:comment1.partition(start)[-1].partition(end)[0]
您也可以使用reg-exp,如re.findall('due-on:(.*)\,'comment)
。它似乎更容易阅读。