1

I have asked a previously one question where I was impressed with unpacking approach shared by one person I am bit playing with bit to print patterns

I want to pad the single digit with zero to make it equivalent to 2 digit number length

I tried zfill but not throwing me error : AttributeError: 'int' object has no attribute 'zfill'

Code :

n=15
for i in range(1,n+1):
  print(*range(1,n+1))
  n = n -1 

Expected output :

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
01 02 03 04 05 06 07 08 09 10 11 12 13 14
01 02 03 04 05 06 07 08 09 10 11 12 13
01 02 03 04 05 06 07 08 09 10 11 12
01 02 03 04 05 06 07 08 09 10 11
01 02 03 04 05 06 07 08 09 10
01 02 03 04 05 06 07 08 09
01 02 03 04 05 06 07 08
01 02 03 04 05 06 07
01 02 03 04 05 06
01 02 03 04 05
01 02 03 04
01 02 03
01 02
01

2 Answers2

1

You can use format string syntax 02.

change the line : print(*range(1,n+1)) to print(*(f"{i:02}" for i in range(1, n + 1)))

Full code:

n = 15
for i in range(1, n + 1):
    print(*(f"{i:02}" for i in range(1, n + 1)))
    n = n - 1

output:

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
01 02 03 04 05 06 07 08 09 10 11 12 13 14
01 02 03 04 05 06 07 08 09 10 11 12 13
01 02 03 04 05 06 07 08 09 10 11 12
01 02 03 04 05 06 07 08 09 10 11
01 02 03 04 05 06 07 08 09 10
01 02 03 04 05 06 07 08 09
01 02 03 04 05 06 07 08
01 02 03 04 05 06 07
01 02 03 04 05 06
01 02 03 04 05
01 02 03 04
01 02 03
01 02
01

Another option is to use zfill like :

print(*(str(i).zfill(2) for i in range(1, n + 1)))

you need to convert the i into str because zfill is a method of string objects.

S.B
  • 13,077
  • 10
  • 22
  • 49
0

There are many ways to do this. Here's one of them:

n = 15

for i in range(1, n+1):
    print(' '.join(f'{j:02d}' for j in range(1, n-i+2)))
DarkKnight
  • 19,739
  • 3
  • 6
  • 22