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
  • 361
  • 3
  • 13

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,858
  • 5
  • 23
  • 34
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
  • 18,333
  • 14
  • 83
  • 102