pythonlistpython-re

Add string before character in nested list using python


I have a long nested list of times. I want to add '0' before one-digit numbers of time in the list (like result list). I have tried the below code block, but it doesn't work. I know that using Regular expression is the best solution for the issue. But I don't have any experiences of re package. How can I solve the issue using re package or any other solution?

mylist = [
    ['x', '6:00 - 9:30 AM - 10:30 AM - 2:00 PM - 5:00 PM - 9:00 PM'],
    ['y',  '7:30 AM - 2:30 PM, 7:30 AM - 2:30 PM, 7:30 AM - 1:30 PM']
]

result = [
    ['x', '06:00 - 09:30 AM - 10:30 AM - 02:00 PM - 05:00 PM - 09:00 PM'],
    ['y', '07:30 AM - 02:30 PM, 07:30 AM - 02:30 PM, 07:30 AM - 01:30 PM']
]


for idx, (id,name) in enumerate(list3):
    if  len(name.split('-')[0].split(':')[0]) <2 and  len(name.split('-')[1].split(':')[0]) <3:
         list3[idx][1] = '0'+name.split('-')[0] + ' - ' + '0'+ name.split('-')[1].strip()
         # print 1
    if len(name.split('-')[0].split(':')[0]) < 2 and len(name.split('-')[1].split(':')[0]) == 3:
        list3[idx][1] = '0' + name.split('-')[0] + ' - ' +  name.split('-')[1].strip()
    if len(name.split('-')[0].split(':')[0]) == 2 and len(name.split('-')[1].split(':')[0]) < 3:
        list3[idx][1] =  name.split('-')[0] + ' - ' + '0'+name.split('-')[1].strip()

Solution

  • try this, (\d+?:) would match 06:, 09:, 10: .. then use rjust to prefix zero's

    import re
    
    mylist = [['x', '6:00 - 9:30 AM - 10:30 AM - 2:00 PM - 5:00 PM - 9:00 PM'],
              ['y', '7:30 AM - 2:30 PM, 7:30 AM - 2:30 PM, 7:30 AM - 1:30 PM']]
    
    print(
        [[re.sub("(\d+?:)", lambda m: m.group(1).rjust(3, '0'), y) for y in x]
         for x in mylist]
    )
    

    [['x', '06:00 - 09:30 AM - 10:30 AM - 02:00 PM - 05:00 PM - 09:00 PM'],
     ['y', '07:30 AM - 02:30 PM, 07:30 AM - 02:30 PM, 07:30 AM - 01:30 PM']]