2

I am writing int to a file. if the number is 0, then i want to write it in file as 0000. currently

o.write(str(year))

writes only 0.

How can it be done?

neogeomat
  • 352
  • 2
  • 12

2 Answers2

1

try this: (the essence is using zfill to show the number of zeros you want in the most succinct way)

if int(my_number_as_string) == 0:
    print my_number_as_string.zfill(4) 
labheshr
  • 2,568
  • 2
  • 20
  • 30
0

Following function will help you to pad zeros

def add_nulls2(int, cnt):
    nulls = str(int)
    for i in range(cnt - len(str(int))):
        nulls = '0' + nulls
    return nulls

Output

>>> add_nulls2(5,5)
'00005'
>>> add_nulls2(0,5)
'00000'
>>> 
Subodh Ghulaxe
  • 17,943
  • 14
  • 81
  • 99