I'm trying to format my data on 2 places. If it contains only 1 element, it should append 0 to it. For example new_time = [10,52]
My desire output is [10,52]
For [10,5] My desire output is [10,05] I read about this method new_time = [new_time[0],new_time[1]:02]
. But output of this is invalid syntax. Does anybody know why it isn't work? I did similar exercise and it works.
CodePudding user response:
It is not possible for integers to be denoted with leading zeroes, and it is by design.
Try to run this statement into your python console: print(05)
. You would get an error stating that
SyntaxError: leading zeros in decimal integer literals are not permitted;
use an 0o prefix for octal integers
But you can typecast integers into strings and logically put leading zeroes if you need.
CodePudding user response:
Integers(and Floats) can not be written with leading zeros. What you can do in this case is to convert them to string like this:
new_time = [10,5]
ls= [f'{_:02}' for _ in new_time]
print(ls) # Returns ['10', '05']
CodePudding user response:
I'm afraid you can not display left-zeros for values of type int
, unless you change them into str
:
new_time = ["d"%i for i in new_time]
for which, new_time
outputs:
['10', '05']
CodePudding user response:
new_time = [10, 5]
formated_time = []
for item in new_time:
if item < 10:
time = f"0{item}"
formated_time.append(time)
if item >= 10:
time = item
formated_time.append(time)
print(formated_time)
"""note:but while using it again you should use type('int') before the item"""