I get a list out looking like this: (hours)
list = ['02:00', '01:00', '03:00', '00:00', '04:00', '05:00', '06:00', '23:00', '24:00', '07:00', '22:00', '14:00', '13:00', '15:00', '21:00', '08:00', '16:00', '12:00', '20:00', '17:00', '11:00', '18:00', '09:00', '10:00']
in the end of my function it looks like this when I sort out the list:
list = nsmallest(HoursPerDay, my_dict, key=my_dict.get)
return [i.strip(':0') for i in list]
And it gives me this: list = ['2', '1', '3', '', '4', '5', '6', '23', '24', '7', '22', '14', '13', '15', '21', '8', '16', '12', '2', '17', '11', '18', '9', '1']
Works fine on every hour except for 20:00 that it makes into 2 instead of 20 and make 00:00 into nothing. How do I solve this? I have tried some regex generators too but I can´t get it right.
CodePudding user response:
Rather than stripping you should be splitting. Something like this:
inlist = ['02:00', '01:00', '03:00', '00:00', '04:00', '05:00', '06:00', '23:00', '24:00', '07:00', '22:00', '14:00', '13:00', '15:00', '21:00', '08:00', '16:00', '12:00', '20:00', '17:00', '11:00', '18:00', '09:00', '10:00']
outlist = [f"{int(e.split(':')[0])}" for e in inlist]
print(outlist)
Output:
['2', '1', '3', '0', '4', '5', '6', '23', '24', '7', '22', '14', '13', '15', '21', '8', '16', '12', '20', '17', '11', '18', '9', '10']
Note:
The conversion to int and back to string effectively removes any leading zero
CodePudding user response:
strip
default behaviour as given in python documentation is
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.
'00010:010:000'.strip(':0') # it will remove all available combination of ':0'
# you will get '10:01'
Now for your specific requirement
[i.rstrip('0').rstrip(':') for i in list]
If you want to retain zeroes from right side after first 0 removed then use
import re
list = ['02:00', '01:00', '03:00', '00:00', '04:00', '05:00', '06:00', '23:00', '24:00', '07:00', '22:00', '14:00', '13:00', '15:00', '21:00', '08:00', '16:00', '12:00', '20:00', '17:00', '11:00', '18:00', '09:00', '10:00']
[re.sub(r'0 (. )', r'\1', i.rstrip('0').rstrip(':')) for i in list]
# ['2', '1', '3', '0', '4', '5', '6', '23', '24', '7', '22', '14', '13', '15', '21', '8', '16', '12', '20', '17', '11', '18', '9', '10']
CodePudding user response:
If we use the following snippet, your desired result can be achieved.
[(i.removesuffix(':00')).lstrip('0') or '0' for i in list]
- Removing the :00 suffix.
- Removing leading zero.
- Special case for "00:00".
Another alternate solution using the regex:
[re.sub("\:00$", "", i).lstrip('0') or '0' for i in list]