How to replace and split a simple data string using Python into 2 separate outputs

Question:

This is the input data I am dealing with.

November (5th-26th)

What I want to do is get 2 seperate outputs from this data string. i.e. {November 5th} and {November 26th}

I currently use this python script to remove the uneccesary characters in it

Name = input_data['date'].replace("(", "").replace(")", "")

output = [{"Date": Name}]

and use other no code formating tools (Zapier) to split the data and make the output come as {November 5th} and {November 26th}

I would like to know form you guys if there is a single python code I could use to get the desired output without using other formating tools.

Thanks

I haven’t treid anything with the code yet.

Asked By: Fahad Sheji

||

Answers:

A simple regex will handle that nicely

import re

value = "November (5th-26th)"
month, date_from, date_to = re.match(r"(w+)s+((.*)-(.*))", value).groups()
print([month, date_from, date_to])  # ['November', '5th', '26th']

result = [f"{month} {date_from}", f"{month} {date_to}"]
print(result)  # ['November 5th', 'November 26th']
Answered By: azro

You could do it like this in two steps:

string = "November (5th-26th)"
month, days = [x.strip('()') for x in string.split(' ')]
start, end = days.split('-')

output = {'date_range' : [f"{month} {start}", f"{month} {end}"]}
print(output)
{'date_range': ['November 5th', 'November 26th']}

2nd task:
Similar approach, replace the & (with leading and trailing space) with e.g , then seperate the data by splitting again similar to before.

string2 = "December 10th & 11th"
string2 = string2.replace(' & ', ',')
month, days = string2.split(' ')
start, end = days.split(',')

output = {'date_range' : [f"{month} {start}", f"{month} {end}"]}
print(output)
{'date_range': ['December 10th', 'December 11th']}
Answered By: Rabinzel

A simple tokenisation and split should do the trick:

s = 'November (5th-26th)'
m, d = s.split()
for dt in d[1:-1].split('-'):
    print(f'{{{m} {dt}}}')

Output:

{November 5th}
{November 26th}
Answered By: Cobra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.