-1

I wrote a function that reads from a file and checks each line according to some conditions. Each line in the file contains a number. In the function itself, I'd like to add to this number and check it again so I tried the following:

str(int(l.strip())+1)) # 'l' being a line in the file

I noticed that I got some faulty results each time I cast a number with leading zeroes. (The file contains every possible 6-digit number, for example: 000012).

I think that the conversion to integer just discards the unnecessary leading zeroes, which throws off my algorithm later since the string length has changed.

Can I convert a string to an integer without losing the leading zeores?

Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
Sparkas
  • 143
  • 1
  • 9
  • 3
    What constitutes a faulty result? What are you getting and how does it differ from what you want? – a p Aug 17 '15 at 20:33
  • 1
    See this question for information on printing formatted zeroes; there's no sense in an `int` preserving leading zeroes. You'll want to pad them back in when you write out your results, whatever those are, as strings: http://stackoverflow.com/questions/134934/display-number-with-leading-zeros – a p Aug 17 '15 at 20:35
  • Cleaned up and spaced out your question some. Let me know if I have conflicted with your original intent. – Two-Bit Alchemist Aug 17 '15 at 20:45
  • Thanks for the edit, you probably made clear some missing info for other users! – Sparkas Aug 17 '15 at 20:59

1 Answers1

2

If you want to keep the zero padding on the left you should convert the number to a string again after the addition. Here's an example of string formatting for zero padding on the left for up to six characters.

In [13]: "%06d" % 88
Out[13]: '000088'
Diego Allen
  • 4,623
  • 5
  • 30
  • 33
  • Thanks! I can definately work with this. Edited it to: "%06d" % (int(l.strip())+1). Thanks again! – Sparkas Aug 17 '15 at 21:04