Why leading zero not possible in Python's Map

2019-08-10 22:14发布

问题:

This question already has an answer here:

  • Python cannot handle numbers string starting with 0. Why? 2 answers

What is the reason that you cannot use zero at the beginning of a number when converting the number to a sequence?

Code example

map(int,str(08978789787))

which gives Syntax error.

I would like to convert numbers which leading digit is zero to a sequence. How can you convert such a number to a sequence?

回答1:

This happens because the leading zero means you are writing an octal number and you can't have 9 or 8 in an octal number. See:

>>> a = 0123
>>> a
83
>>> a = 010
>>> a
8

You can just do:

>>> map(int, '08978789787')
[0, 8, 9, 7, 8, 7, 8, 9, 7, 8, 7]


回答2:

The "leading 0 in an integer means it's in octal notation" meme is a peculiar one which originated in C and spread all over the place -- Python (1.* and 2.*), Perl, Ruby, Java... Python 3 has eliminated it by making a leading 0 illegal in all integers (except in the constructs 0x, 0b, 0o to indicate hex, binary and octal notations).

Nevertheless, even in a hypothetical sensible language where a leading 0 in an int had its normal arithmetical meaning, that is, no meaning whatsoever, you still would not obtain your desired result: 011 would then be exactly identical to 11, so calling str on either of them would have to produce identical results -- a string of length two, '11'.

In arithmetic, the integer denoted by decimal notation 011 is identical, exactly the same entity as, indistinguishable from, one and the same with, the integer denoted by decimal notation 11. No hypothetical sensible language would completely alter the rules of arithmetic, as would be needed to allow you to obtain the result you appear to desire.

So, like everybody else said, just use a string directly -- why not, after all?!



回答3:

Python: Invalid Token

Use:

map(int,"08978789787")


回答4:

"How can you convert such a number to a sequence?"

There is no "such a number". The number 1 does not start with a 0. Numbers do not start with zeros in general (if they did, you would need to write an infinite amount of zeros every time you write a number, and that would obviously be impossible).

So the question boils down to why you are writing str(08978789787)? If you want the string '08978789787', you should reasonably just write the string '08978789787'. Writing it as a number and the converting it to a string is completely pointless.