1 votes

Why doesn't Python accept leading zero?

My problem is that I cannot use leading zero in variables or other means of capturing data such as the PyQt5.QLineEdit.text(). No way, not even transforming digits into strings.

VariableUno = str(01)
VariableDos    = 02
print (VariableUno,VariableDos)

1voto

FJSevilla Points 29084

In Python 3.x the reason is historical more than anything else, leading zeros in a non-zero decimal number are not allowed to avoid confusion by allowing disambiguation with C language style octal literals used prior to Python 3.

  • To define a literal int in octal before Python 3, the syntax was:

    "0" octdigit+

    For example:

    diecisiete_octal = 021
  • In Python >= 3.x instead the syntax is:

    "0" ("o" | "O") octdigit+

    For example:

    diecisiete_octal = 0o21
    diecisiete_octal = 0O21

Therefore, you cannot define literals with leading zeros unless it is a 0. The main motivation for this change of syntax of 0 a 0o/0O is explained in the PEP that developed it at the time:

The default octal representation of integers is silently confusing to people unfamiliar with C-like languages. It is extremely easy to inadvertently create an integer object with the wrong value, because '013' means 'decimal 11', not 'decimal 13', to the Python language itself, which is not the meaning that most humans would assign to this literal.

Which loosely translated would be something like this:

The default octal representation of integers is implicitly confusing to people unfamiliar with C-like languages. It is extremely easy to inadvertently create an integer object with the wrong value, because '013' means 'decimal 11', not 'decimal 13', for the Python language itself, which is not the meaning most people would assign to this literal.

If you need to represent an integer with leading zeros (typical in dates for example) just convert it to a string and format it appropriately:

mes = 2
mes_str = "{:02d}".format(mes)
print(mes_str)

Or if you use Python>= 3.6 you can also use formatted string literals:

mes = 2
mes_str = f"{mes:02d}"
print(mes_str)

With 02d indicate that you want the integer to have always two digits, in case of having less, it must be completed with zeros to the left. For more information see:

If you enter the data from the keyboard via input() or some widget that returns a text string, you can convert it to int no problems:

>>> int("02")
2

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X