Skip to main content
 首页 » 编程设计

Python oct() 函数缺少预期的 0oXXXX 前缀

2025年02月15日752php

不确定这是系统问题还是版本问题,但是在调用嵌入式 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 "p​​rint 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.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 == 01234  # ran in Python 2.7.13 
True 

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

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

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