0

First, yes I know that str(n).zfill(width) works very well at padding zeros in front of digits.

But has anybody tried writing their own algorithm for this? I tried...

def printNodeNames(name, first, last, numPadZeros):
    for i in range(first, last+1):
        s = ""
        for j in range(0, numPadZeros):
            if i >= 10**j and i < 10**(j+1):
                zeros = ""
                for k in range(0, numPadZeros-j):
                    zeros = zeros + "0"
                s = name + zeros + str(i)
        nodes[i-1:i] = [s]
    return nodes

The above function is suppost to print node names of a compute cluster, BUT IT DOES NOT WORK. Example:

>>> printNodeNames('node', 1, 12, 1)
['node01', 'node02', 'node03', 'node04', 'node05', 
 'node06', 'node07', 'node08', 'node09', '', '', '']

As just an excercise, can anybody figure out why it doesn't work?

Dan Mantyla
  • 1,840
  • 1
  • 22
  • 33

1 Answers1

4

You are only assigning a value to s if your if statement is true. In the case of node 10 and above, the if statement is never true so s remains "".

To change it move the assignment of s out of the inner for block. and set zeros = "" before the for block.

ajon
  • 7,868
  • 11
  • 48
  • 86