2017-05-14 22 views
2

不知道这是系统还是版本问题,但在调用嵌入式oct()函数时我缺少预期的八进制前缀?这里是我的榜样Python oct()函数缺少预期的0oXXXX前缀?

# Base conversion operations 
print 'x = 1234 ' ; x = 1234    # all numbers are base10 derivs 
print 'bin(x) ' , bin(x)     # '0b10011010010' 
print 'oct(x) ' , oct(x)     # '02322' -> missing prefix??? expected: 0o02322??? 
print 'hex(x) ' , hex(x)     # '0x4d2' 

# Using the format() function to suppress prefixes 
print 'format(x, \'b\')' , format(x, 'b') # bin conversion 
print 'format(x, \'o\')' , format(x, 'o') # oct conversion 
print 'format(x, \'x\')' , format(x, 'x') # hex conversion 

# version: Python 2.7.13 
# output: 
# x = 1234 
# bin(x) 0b10011010010 
# oct(x) 02322    <- unexpected output 
# hex(x) 0x4d2 
# format(x, 'b') 10011010010 
# format(x, 'o') 2322 
# format(x, 'x') 4d2 

我会非常非常期望在python -c "print oct(1234)"一回是'0o02322'还是我失去了一些东西明显?

__builtin__.py__

def oct(number): # real signature unknown; restored from __doc__ 
    """ 
    oct(number) -> string 

    Return the octal representation of an integer or long integer. 
    """ 
    return "" 

走在华侨城定义返回一个int的八进制代表应该表达一个前缀字符串?

+2

Python 2.7版同时接受0×××××,0oxxxx而Python 3.x中只接受0oxxxx。 – falsetru

+1

过去,八进制数仅以前导零显示。因此,0123意味着八进制“0123”==十进制“83”。然而,趋势是将八进制表示为“0o123”,类似于十六进制表示“0x53”。而Python2是旧的。 :-) – JohanL

+0

@falsetru同意了,但我不在 – ehime

回答

1

在Python 2.6之前,只允许使用0XXXXX八进制表示法。在Python 3.x, only 0oXXXXX octal representation is allowed

为了便于从Python 2.x迁移到Python 3.x,Python 2.6添加了对0oXXXX的支持。见PEP 3127: Integer Literal Support and Syntax - What's new in Python 2.6

>>> 0o1234 ==# ran in Python 2.7.13 
True 

Python 2.x中oct的行为没有因为向后兼容性而改变。

如果你愿意,你可以定义oct你自己的版本:

>>> octal = '{:#o}'.format 
>>> octal(10) 
'0o12' 
+0

接受并加上一个,谢谢你一个优秀和详细的答案 – ehime