2

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'

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Jesh Kundem
  • 960
  • 3
  • 18
  • 30

3 Answers3

6

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 :)

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
4

The outcome isn't as what you expected because the int() function ignores the leading zeroes. Leading zeroes aren't stored in an integer.

What does the trick is

a = '00001'
b = int(a) + 1
print str(b).zfill(5)

The 5 here means the number has to be 5 digits. What zfill(number) does is add zeroes to the beginning of the string until the string has a length of number characters (digits in this case).

Hope it helps.

Kevin
  • 685
  • 1
  • 7
  • 16
1
a = '00001'

b = str(int(a) + 1).zfill(5)

>>> b
'00002'

or simply...

a = 1
a += 1
print(str(a).zfill(5))
Alexander
  • 105,104
  • 32
  • 201
  • 196