vendredi 14 février 2020

Replace value if it starts with certain character

I have a following list and I am trying to replace any value which starts with 23: to 00:00:00.00

tc = ['00:00:00.360',
      '00:00:00.920',
      '00:00:00.060',
      '00:00:02.600',
      '23:59:55.680',
      '00:00:05.960',
      '00:00:01.040',
      '00:00:01.140',
      '00:00:01.060',
      '00:00:01.480',
      '00:00:00.140',
      '00:00:00.280',
      '23:59:59.800',
      '00:00:01.200',
      '00:00:00.400',
      '23:59:59.940',
      '00:00:01.220',
      '00:00:00.380']

I am able to get what I need using regex,

tc = [re.sub(r'(\b23:)(.*)',r'00:00:00.00', item) for item in tc]

and it gives me expected result as per below,

['00:00:00.360',
 '00:00:00.920',
 '00:00:00.060',
 '00:00:02.600',
 '00:00:00.00',
 '00:00:05.960',
 '00:00:01.040',
 '00:00:01.140',
 '00:00:01.060',
 '00:00:01.480',
 '00:00:00.140',
 '00:00:00.280',
 '00:00:00.00',
 '00:00:01.200',
 '00:00:00.400',
 '00:00:00.00',
 '00:00:01.220',
 '00:00:00.380']

But if I use the below method without using regex, then the result is not what I expect,

tc = [item.replace(item, '00:00:00.00') for item in tc if item.startswith('23:')]

Result:

['00:00:00.00', '00:00:00.00', '00:00:00.00']

The resultant list is only with replaced items and not the whole list. How to I use the above method to get complete list?

Aucun commentaire:

Enregistrer un commentaire