'Python how to split a single string in a list, into various strings by splitting it with multiple delimiters
I am writing a program for a calendar and in a specific function, I have to add/delete a calendar event. In my delete_event function, I am taking the already given list of events [date;time+duration] and I essentially need to split each portion of the string in the list. Ex. [2/3/2022;10:00+50] needs to be [2/3/2022, 10:00, 50]. I have already attempted using the re module but it still wouldn't split properly. Here's my code:
def delete_event(self,date,time):
'''Delete the event at the specified date and time'''
event_listt = str(self.event_list)
for event in event_listt:
event_list = re.split(', |_|-|!|\+|;', event)
for event in event_list:
event_date = event_list[0]
event_time = event_list[1]
try:
if event_date == date and event_time == time:
del event
print("Event successfully deleted.")
except:
print("Event was not deleted.")
return False
Solution 1:[1]
You can use named capture groups to create a dictionary for each event from a list of events:
import re
pattern = re.compile(r"(?P<date>\d{1,2}\/\d{1,2}\/\d{4});(?P<time>\d{1,2}:\d{1,2})\+(?P<duration>\d+)")
events = ["2/3/2022;10:00+50", "2/4/2022;11:00+40"]
event_data = [match.groupdict() for event in events for match in pattern.finditer(event)]
Output:
[{'date': '2/3/2022', 'time': '10:00', 'duration': '50'},
{'date': '2/4/2022', 'time': '11:00', 'duration': '40'}]
Note this will also work if the strings have square brackets in them for some reason:
In [4]: events = ["[2/3/2022;10:00+50]", "[2/4/2022;11:00+40]"]
In [5]: [match.groupdict() for event in events for match in pattern.finditer(event)]
Out[5]:
[{'date': '2/3/2022', 'time': '10:00', 'duration': '50'},
{'date': '2/4/2022', 'time': '11:00', 'duration': '40'}]
Solution 2:[2]
I would be tempted to not use regular expressions at all and do it with str.replace()
and str.split()
. Your delimiters are semicolon (;
) and plus sign(+
).
You could replace plus sign with semicolon and then split the string:
event_list = event.replace('+', ';').split(';').
But if you want to stick with regular expressions, I think you can put all of your delimiters in square brackets and it's treated like a list of characters. However, +
is a special character and you'll have to escape it with a forward slash:
event_list = re.split('[;\+]', event)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ddejohn |
Solution 2 | bfris |