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

标签 python function octal

不确定这是系统还是版本问题,但在调用嵌入式 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'

关于Python oct() 函数缺少预期的 0oXXXX 前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43960601/

相关文章:

c - 如果输入的值大于 3,则函数将永远递归运行

python-2.7 - 如何在 Python 中解析具有八进制值的 char 数组?

python - 禁止向 Python 子类添加新方法

javascript - 调用随机函数 Javascript,但不是两次相同的函数

python - 保留函数实现的顺序

python - 正则表达式和八进制字符

python - 使用f-strings python格式化具有相同宽度的数字

python - 关于 read_file() 的 Geopandas 警告

python - 使用自定义信息填写日历