0

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.

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
MiguelP
  • 416
  • 2
  • 12

2 Answers2

3

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

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
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44