3
>>> num = int('0241034812')
>>> print(num)
241034812
>>> 

In the above code, I'm setting the variable num to 0241034812; however, when I print the variable it deletes the first zero.

Why is this happening?

jscs
  • 63,694
  • 13
  • 151
  • 195
pancheke
  • 84
  • 1
  • 1
  • 7
  • 5
    What would you expect? `241034812` and `0241034812` are the same number and they have the same internal representation – Niklas B. Mar 23 '14 at 22:03
  • 1
    If you want to keep the zero, you have to store it as a string, not as an int. But you'll need to convert to int to actually do arithmetic. – sgauria Mar 23 '14 at 22:05
  • 4
    Python integers have *no* facility to store 'leading zeros', because it makes little sense to do so. Leading zeros have no meaning for numeric values. – Martijn Pieters Mar 23 '14 at 22:05

4 Answers4

4

Integers are stored/displayed as a "normal" number, not the string value. If you want to display the number prefixed with zeroes you can do that when displaying the variable.

You can use the following syntax to add leading zeros to an integer:

print "%010d" % (241034812,)

The example above will display the integer 241034812 with 10 digits as 0241034812.

HAL
  • 2,011
  • 17
  • 10
1

I'm setting the variable 'num' to '0241034812'

No, you're setting it to 241,034,812: an integer value, about two hundred forty million. If you want to set it to '0241034812', you should use a string rather than an integer. That is, you should drop the call to int:

>>> num = '0241034812'
>>> print(num)
0241034812
>>> 
ruakh
  • 175,680
  • 26
  • 273
  • 307
1

If you're storing some number in a format where a leading zero would be useful/significant (maybe a barcode, ISBN, or the like), you can re-add them when converting back into a string using .format

>>> num = int('0241034812')
>>> print('{:010d}'.format(num))
0241034812

Briefly, the first 0 in the format spec means to add leading zeros if not present to fill 10 (the 10) characters.

Nick T
  • 25,754
  • 12
  • 83
  • 121
  • 2
    If the leading zeroes are significant, I would argue that you do not have a number. A number is a quantity. You wouldn't try to add two ISBNs, or phone numbers. Instead, you have a string, even if it's a string made up only of digits. – jscs Mar 23 '14 at 22:20
0

You wanted to print your integer to a specific zero-padded width, use string formatting. The format() function, for example:

>>> num = 241034812
>>> print(format(num, '010d'))
0241034812

or print the original string from which you parsed the integer in the first place.

Integers do not store a 'print width' or any number of leading 0 digits.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343