-3

Is there any way to display a list in Python with leading zeroes on numbers <= 9, but without using strings?

I'm helping a student on an assignment, and his module calculates a list of random numbers and returns that list to his main program. So it's not possible to use format() in this situation.

import random
list = []
x = 0
while x < 6:
    number = random.randint(1,70)
    if number <= 9:
        temp = str(number)
        temp = temp.zfill(2)
        list.append(temp)
    else:
        list.append(str(number))
    x+=1

print(list)

Example output:

['16', '41', '17', '40', '01', '28']

Desired output:

[16, 41, 17, 40, 01, 28]
Python guy
  • 99
  • 2
  • 3
  • 9
  • No, you cannot do that. `01` is an octal literal in 2.x (where it will always be displayed in a list as the decimal integer `1`) and a syntax error in 3.x. You could build a string that is specifically `'[16, 41, 17, 40, 01, 28]'`. – jonrsharpe Oct 31 '16 at 18:16
  • You cannot. `08` and `09` are not valid numbers in python. – Eli Sadoff Oct 31 '16 at 18:17

1 Answers1

0

Well, you could store the numbers with no leading zeroes, then when printing you could format it as string with leading zeroes:

import random
lst = [] # Avoid using keywords
x = 0
while x < 6:
    number = random.randint(1,70)
    lst.append(number)
    x+=1

print("[" + ", ".join(['%02d' % x for x in lst]) + "]")

The last line is quite weird, let's break it down:

  • '%02d' % x is string formatting

  • ['%02d' % x for x in lst] is list comprehension in python.

  • ", ".join(...) concatenates all the elements of the list separating them with a comma.

However, the cool thing about python is that you get to do complex things in a simple manner, for instance your code could be reduced to a couple lines of code:

import random
lst = random.sample(range(1, 70), 6)
print("[" + ", ".join(['%02d' % x for x in lst]) + "]")
Community
  • 1
  • 1
Rodolfo
  • 573
  • 2
  • 8
  • 18