显示一个八进制值作为它的字符串表示

display an octal value as its string representation

我在将八进制数转换为字符串时遇到问题。

p = 01212
k = str(p)
print k

结果是 650 但我需要 01212。我怎样才能做到这一点?提前致谢。

一种方法是使用 Format Mini Specification Language:

中的 o 格式字符

示例:

>>> x = 01212
>>> print "0{0:o}".format(x)
01212

'o' Octal format. Outputs the number in base 8.

注意: 你仍然需要在前面添加 0除非你使用内置函数 oct() ).

更新: 如果您使用的是 Python 3+:

$ python3.4
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 01212
  File "<stdin>", line 1
    x = 01212
            ^
SyntaxError: invalid token
>>> x = 0o1212
>>> print(oct(x))
0o1212
>>> print("0o{0:o}".format(x))
0o1212

您的数字 p 是实际的 而不是该值的 表示 。所以它实际上是 650<sub>10</sub>, 1212<sub>8</sub>28a<sub>16</sub>,同时.

如果您想将其视为八进制,只需使用:

print oct(p)

根据以下成绩单:

>>> p = 01212
>>> print p
650
>>> print oct(p)
01212

那是 Python 2(你似乎正在使用它,因为你使用八进制文字的 0NNN 变体而不是 0oNNN)。

Python 3 的表示略有不同:

>>> p = 0o1212
>>> print (p)
650
>>> print (oct(p))
0o1212