Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display an octal value as its string representation

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.

like image 644
maphongba008 Avatar asked May 11 '15 05:05

maphongba008


People also ask

How do you find the octal value of a string in Python?

Python oct() function is used to get an octal value of an integer number. This method takes an argument and returns an integer converted into an octal string. It throws an error TypeError if argument type is other than an integer.

What is octal string?

1. A. The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7, that is to say 10octal represents eight and 100octal represents sixty-four.

What is octal string in Python?

Definition and Usage. The oct() function converts an integer into an octal string. Octal strings in Python are prefixed with 0o .

How do I print an octal number?

Using %o format specifier in printf, we can print the octal numbers.


1 Answers

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
like image 150
paxdiablo Avatar answered Oct 10 '22 06:10

paxdiablo