Remove string from left and right side of date using python and update as new string

Viewed 39
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

Is there any solution to get "I went to market on October 29,2017 on London" by removing "I" from October 29,2017I

There are much more cases like above

2 Answers

Try using re.sub and str.join with a list comprehension:

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()]))

Output:

I went to market on October 29,2017 on London

As long as what you are looking for is extracting the date from a sentence in a rigid format (e.g. '12-7-2021'), you can do it using regular expressions:

import re

ss = ['12-7-2021mma', 'kk12/7/2021', 'yy12/9/2021kko']

for ss1 in ss:
    ss_date = re.match(r'[^0-9]*(\d\d?[-/]\d\d?[-/]\d{4})[^0-9]*', ss1)


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

You get:

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