【发布时间】:2017-10-13 02:57:53
【问题描述】:
不确定这是系统问题还是版本问题,但在调用嵌入式 oct() 函数时缺少预期的八进制前缀?这是我的例子
# 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__ 开始对 oct 的定义
def oct(number): # real signature unknown; restored from __doc__
"""
oct(number) -> string
Return the octal representation of an integer or long integer.
"""
return ""
返回一个 int 的八进制表示应该表示一个前缀字符串?
【问题讨论】:
-
Python 2.7 接受 0xxxxx、0oxxxx 而 Python 3.x 只接受 0xxxx。
-
在过去,八进制仅以前导零显示。因此 0123 表示八进制
0123== 十进制83。然而,趋势是将八进制表示为0o123,类似于十六进制表示0x53。而且 Python2 很旧。 :-) -
@falsetru 同意了,但我在看外面不是在里面
-
@ehime,正如 JohanL 所说,旧版本的 Python 2.x 使用
0xxx表示。oct应该保持向后兼容性。在 Python 2.x 中改变行为会混淆使用它的人。 Python 2.7 接受 0oxxxx 表示,以帮助更轻松地迁移到 Python 3.x。 -
如何定义您自己的
oct版本?octal = '{:#o}'.format