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?

5
  • related stackoverflow.com/questions/339007/… Commented Sep 21, 2012 at 14:50
  • Your code refers to nodes but doesn't define it. Commented Sep 21, 2012 at 14:52
  • true, i just copy/pasted a snippit from a larger function, and forgot that line Commented Sep 21, 2012 at 15:01
  • Why would you write a loop to create your zeroes rather than just doing "0" * numPadZeros? Commented Sep 21, 2012 at 15:08
  • hmm...probably because I DIDN'T KNOW YOU COULD DO THAT. smart ass... Commented Sep 21, 2012 at 20:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.