Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a value with leading zeroes?

Tags:

python

What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".

I can think of a couple ways, but I want to see if someone comes up with something slick.

like image 946
Huuuze Avatar asked Feb 25 '09 20:02

Huuuze


2 Answers

int('00000001') + 1

if you want the leading zeroes back:

"%08g" % (int('000000001') + 1)
like image 157
ʞɔıu Avatar answered Sep 27 '22 16:09

ʞɔıu


Use the much overlooked str.zfill():

str(int(x) + 1).zfill(len(x))
like image 40
recursive Avatar answered Sep 27 '22 18:09

recursive