Integers with leading zeroes
Steven D'Aprano
steve at pearwood.info
Wed Jul 22 02:55:48 CEST 2015
On Wed, 22 Jul 2015 03:21 am, Antoon Pardon wrote:
> On 07/19/2015 07:39 AM, Steven D'Aprano wrote:
>> In Python 2, integer literals with leading zeroes are treated as octal,
>> so 09 is a syntax error and 010 is 8.
>>
>> This is confusing to those not raised on C-style octal literals, so in
>> Python 3 leading zeroes are prohibited in int literals. Octal is instead
>> written using the prefix 0o, similar to hex 0x and binary 0b.
>>
>> Consequently Python 3 makes both 09 and 010 a syntax error.
>>
>> However there is one exception: zero itself is allowed any number of
>> leading zeroes, so 00000 is a legal way to write zero as a base-10 int
>> literal.
>>
>> Does anyone use that (mis)feature?
>>
>
> Yes. I like to sometime write numbers with leading zeros.
In Python 2, those numbers will be in octal:
nums = [0000, 0001, 0002, 0003,
0004, 0005, 0006, 0007,
# 0008 and 0009 are syntax errors
0010, ... ]
In Python 3, using leading zeroes is always a syntax error, unless all the
numbers are zero:
# Okay
nums = [0000, 0000, 0000, 0000, ... ]
# Fails
nums = [0000, 0001, 0002, 0003, ...]
I'm not interested in the Python 2 case with octal numbers. Can you show an
example of how you would use this in Python 3? Or at least explain what
benefit you get from typing out a block of all zeroes by hand, instead of
(say) this?
nums = [0]*10
> Sometimes these numbers represent codeblocks of a fixed
> number of digits. Always writing those numbers with this
> number of digits helps being aware of this. It is also
> easier for when you need to know how many leading zero's
> such a number has.
I'm not sure what you mean here. Python ints don't have a fixed number of
digits.
--
Steven
More information about the Python-list
mailing list