开发者

Number in python - 010 [duplicate]

This question already has answers here: 开发者_如何学Go Closed 10 years ago.

Possible Duplicate:

How do you express binary literals in Python?

When using the interactive shell:

print 010

I get back an 8.

I started playing around using other numbers having zeroes before (0110 = 72, 013 = 11) but I could not figure it out...

What is going on here?


Numbers entered with a leading zero are interpreted as octal (base 8).

007 == 7
010 == 8
011 == 9


Python adopted C's notation for octal and hexadecimal literals: Integer literals starting with 0 are octal, and those starting with 0x are hex.

The 0 prefix was considered error-prone, so Python 3.0 changed the octal prefix to 0o.


like many languages, an integer with a leading zero is interpreted as an octal. this means that it's base eight. for example, 020 has decimal value 16 and 030 has decimal value 24. for the sake of completeness, this is how it works. value takes a string and returns the decimal value of that string interpreted as an octal. It doesn't do any error checking so you have to make sure that each digit is between 0 and 8. no leading 0 is necessary.

    def value(s):
        digits = [int(c) for c in s]
        digits.reverse()
        return sum(d * 8**k for k, d in enumerate(digits))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜