Displays an octal value as its string representation

I had a problem converting an octal number to a string.

p = 01212
k = str(p)
print k

Result 650, but I need 01212. How can i do this? Thanks in advance.

+4
source share
2 answers

Your number pis an actual value, not a representation of that value. Thus, it is in fact , and , all at the same time.650101212828a16

If you want to see it as octal, just use:

print oct(p)

according to the following decoding:

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

This is for Python 2 (which you are using as you are using 0NNNthe octal literal variant, not 0oNNN).

Python 3 has a slightly different view:

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

- o Mini Specification Language:

:

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

'o' . 8.

NB: 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
+6

All Articles