1

I'm dealing with strings of the following form '000351'. Think of them as odometer readings. I want to increment them. For example I want to add 1 to '000345' and get '000346'.

The following python code does the job, but appears rather cumbersome. Is there a more elegant way to do this?

s='000345'
t=int(s)
t=t+1
int_to_6digit_string(t)

where the function int_to_6digit_string() is as follows

def int_to_6digit_string(i):
    if i<0 or i>999999:
        return 'argument out of bounds'
    j=str(i)
    if len(j) == 1:
        return '00000'+j
    elif len(j) == 2:
        return '0000'+j
    elif len(j) == 3:
        return '000'+j
    elif len(j) == 4:
        return '00'+j
    elif len(j) == 5:
        return '0'+j
    else:
        return j

1 Answers1

1

use string format: '{:06}'.format(your_number)

Mehdi Pourfar
  • 488
  • 4
  • 13