0
x = 3
for i in range(2**x-1):
    print("{0:0xb}".format(i))

Is there anyway I can do something like this to match binary length with x? so that it would print

000
001
010
011
100
101
110
111

instead of 0 1 01 ... 111 based on my x value?

Wasif
  • 14,755
  • 3
  • 14
  • 34
Eric Choi
  • 13
  • 1
  • Does this answer your question? [Display number with leading zeros](https://stackoverflow.com/questions/134934/display-number-with-leading-zeros) – Qiu Nov 06 '20 at 06:54

1 Answers1

0

You can use a second nested formatting bracket, inside the formatting bracket.

x = 3
for i in range(2**x-1):
    print('{0:0{1}b}'.format(i, x))

Using f-strings this becomes a bit nicer, similar to your idea really, allowing you to inline x:

x = 3
for i in range(2**x-1):
    print(f'{i:0{x}b}')
Jan Christoph Terasa
  • 5,781
  • 24
  • 34