使用python删除日期左右两侧的字符串,并更新为新字符串


string = "I went to market on October 29,2017I on London"
12-7-2021mma  --->12-7-2021
kk12/7/2021   ---> 12-7-2021
yy12/9/2021kko  ---> 12/9/2021

有什么解决方案可以得到";我于2017年10月29日在伦敦市场";通过去除";我"自2017年10月29日起

还有更多类似上述的情况

只要你想要的是以严格的格式(例如"12-7-2021"(从句子中提取日期,你就可以使用正则表达式:

import re
ss = ['12-7-2021mma', 'kk12/7/2021', 'yy12/9/2021kko']
for ss1 in ss:
ss_date = re.match(r'[^0-9]*(dd?[-/]dd?[-/]d{4})[^0-9]*', ss1)

if ss_date is not None:
print(ss_date.group(1))

你得到:

12-7-2021
12/7/2021
12/9/2021

尝试使用具有列表理解的re.substr.join

import re
string = "I went to market on October 29,2017I on London"
print(' '.join([re.sub('[^d+,/-]+', '', i) or i for i in string.split()]))

输出:

I went to market on October 29,2017 on London

最新更新