Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use zfill to make length equivalent to 2 digit length of n

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading