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
>Solution :
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.