0

Is there an elegant solution to do this?

I have a counter running from nmin to nmax. I want to convert these numbers to strings of a fixed length.

Let me illustrate it with an example:

for j in range(nmin,nmax):
    if j<10:
        testval='0000'+str(j)
    elif j>9 and j<100:
        testval='000'+str(j)
    elif .....:
        testval=.....
    else:
        testval='00000'

Although it does the job, I found it rather inelegant. Is there a neater and elegant solution to convert the integer to string of a fixed length?

John Doe
  • 139
  • 1
  • 9
  • 3
    This is exactly what the [`format`](https://docs.python.org/3/library/functions.html#format) function is for. In this case, `format(j, '05')`. The `5` means "minimum width 5 characters", and the `0` means "pad with leading 0s (after a minus sign, if any)". (Not posted as an answer because I'm pretty sure this is a dup, I just need to find the original.) – abarnert Sep 20 '14 at 04:13
  • @abarnert Thanks! Should have Googled better. Sorry. – John Doe Sep 20 '14 at 04:17
  • 1
    This kind of thing can be hard to search for until you know what you're looking for… and once you _do_ know, there's no reason to google, because you can just look in the docs. But anyway, that question has multiple good answers, so the odds are you wouldn't have gotten as lucky as that asker did. :) – abarnert Sep 20 '14 at 04:20

0 Answers0