Jesh Kundem Jesh Kundem - 3 months ago 8
Python Question

Python Str to Int - Very Simple but tricky

I have a small problem, in my GUI application. Which takes only strings to display. I have to perform the following logic. I have a string 'a', which are numbers. It is five digits. I have to increment it by '1' and put it on my GUI again - as "00002" This is the code.

a = '00001'

b = int(a) + 1

print str(b)


Expected Outcome: "00002" - I am getting "2"
I have to make this work for "00001" or "00043" or "00235" or "03356" or "46579" - I am trying to say - It has to work for any number of digits in 'a'

Answer

There are multiple approaches to achieve it:

Approach 1: Using format

>>> format(2, '06d')
'000002'

Approach 2: Using zfill

>>> str(2).zfill(5) 
'00002'

Approach 3: Using %

>>> "%05d" % (2,)
'00002'

Choose whatever suits you the best :)