Issue
Suppose you have a tuple (Hours, minutes) and you want to convert it into 24 hours format hh:mm:ss. Assuming the seconds will always be 0. Eg. (14,0) will be 14:00:00 and (15,0) will be 15:00:00.
So far this is my sketchy way of coming close to the answer:
start_time = (14, 0)
st = ''
for num in start_time:
num = str(num)
if len(num) == 2:
st += num
else:
st += str(num) + '00'
print(st)
Solution
The problems with your current approach:
you're not using any
:
character. After each iteration, check if it's the last by considering the index in your for-loop. If it's not, append a:
character.if
len(num) == 1
, you're inserting two trailing zeros, when it should be one leading zero.
Refactored code:
start_time = (14, 0)
st = ''
# `i` will store the index for each iteration
for i, num in enumerate(start_time):
num = str(num)
if len(num) == 2:
st += num
else:
# If the number of digits is not 2, append a leading '0'
st += '0' + num
# If it's not the last number in the tuple
if i < len(start_time) - 1:
st += ':'
else:
st += ':00'
print(st)
This will output the expected value.
An alternative and compact way of doing this:
def time(t):
# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv Join the mapped values to a single string using `:`
# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv Map this function to each value in this new tuple
# vvvvvvvvvvvvvvv Create a function that adds two trailing zero to a value
# vvvvvvvv Create a new tuple with a trailing zero
return ':'.join(map('{:02d}'.format, t + (0,)))
print(time((14, 0)))
print(time((15, 0)))
Answered By - enzo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.