2017-05-14 23 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