How to unpack a list of ints and print them so they have a preceding zero?

43 Views Asked by At

I have a list of [##, ##, ## ... ##] and I want to unpack it and print it as "##-##-##-...-##" with preceding zeros on the left if the number is less than ten.

Is there a way to do this besides a for loop? I don't want the trailing "-" at the end.

2

There are 2 best solutions below

0
Andrej Kesely On

You can use standard python string formatting + str.join:

lst = [1,2,3,99,8]

s = '-'.join(f'{n:0>2}' for n in lst)
print(s)

Prints:

01-02-03-99-08
0
Talha Tayyab On

You can do with str.format() as well.

lst = [1,2,3,5,10,71,98]

s = '-'.join('{:0>2}'.format(n) for n in lst)
print(s)

#output
01-02-03-05-10-71-98