display an octal value as its string representation
Asked Answered
S

3

12

I've got a problem when converting an octal number to a string.

p = 01212
k = str(p)
print k

The result is 650 but I need 01212. How can I do this? Thanks in advance.

Sienkiewicz answered 11/5, 2015 at 5:34 Comment(0)
R
24

Your number p is the actual value rather than the representation of that value. So it's actually 65010, 12128 and 28a16, all at the same time.

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

print oct(p)

as per the following transcript:

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

That's for Python 2 (which you appear to be using since you use the 0NNN variant of the octal literal rather than 0oNNN).

Python 3 has a slightly different representation:

>>> p = 0o1212
>>> print (p)
650
>>> print (oct(p))
0o1212
Retrenchment answered 11/5, 2015 at 5:36 Comment(2)
In python3 there is slight modificationPeculiarize
@Ajay, added the Py3 stuff though I believe OP is still using Py2. Still it's good to know.Retrenchment
I
14

One way is to usse the o format character from the Format Mini Specification Language:

Example:

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

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

NB: You still have to prepend the 0 (Unless you use the builtin function oct()).

Update: In case you're using 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
Innerve answered 11/5, 2015 at 5:36 Comment(0)
W
0

In addition to the previous answers, if you are using f-strings:

>>> p = 0o1212
>>> print(f"{p:o}")
1212
>>> print(f"{p:#o}")
0o1212

Note that the second notation is also available with format:

>>> print("{:#o}".format(p))
0o1212

But with f-strings available, this will rarely be needed.

Walleyed answered 8/3, 2024 at 6:57 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.