1

将数字转换为序列时,不能在数字开头使用零的原因是什么?

代码示例

map(int,str(08978789787))

这给出了Syntax error.

我想将前导数字为零的数字转换为序列。 如何将这样的数字转换为序列?

4

4 回答 4

14

发生这种情况是因为前导零表示您正在编写八进制数,而八进制数中不能包含 9 或 8。看:

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

你可以这样做:

>>> map(int, '08978789787')
[0, 8, 9, 7, 8, 7, 8, 9, 7, 8, 7]
于 2009-10-10T16:44:34.200 回答
9

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?!

于 2009-10-10T17:14:06.170 回答
4

Python:无效的令牌

利用:

map(int,"08978789787")
于 2009-10-10T16:41:53.863 回答
2

“你怎么能把这样一个数字转换成一个序列?”

没有“这样的数字”。数字 1 不以 0 开头。数字通常不以零开头(如果是这样,则每次写入数字时都需要写入无限数量的零,这显然是不可能的)。

所以问题归结为你为什么写作str(08978789787)?如果你想要字符串'08978789787',你应该合理地只写字符串'08978789787'。将其写为数字并将其转换为字符串是完全没有意义的。

于 2009-10-10T17:48:57.813 回答