Python Forum

Full Version: octal instead of hex
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i can convert binary characters to a literal text form with ascii() (repr() in py2) but it converts most characters to a hexadecimal escape form like '\x00\xff', with simpler control characters like newline converted to '\n'. but i want the octal escape form, like '\000\377'. this form can be used in source code literals. is there a function like ascii() that can give the octal form for bytes in range(256) (ok if it gives control escapes like '\n' for control characters like chr(10) instead of '\012')? i am hoping that i don't need to construct the result myself with a bunch of oct() calls.
Maybe this?

oct(x)¶
Convert an integer number to an octal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
How about:
astring = 'Hello.'
for c in astring:
   print('\\{:03o}'.format(ord(c)), end='')
print()
results:
Output:
/110/145/154/154/157/056
or use list comprehension
[print('\\{:03o}'.format(ord(c)), end='') for c in astring]
I was thinking of how this could be done without using a bunch of oct() as @scaperen asked but didn't get to anything much different than yours proposal
i know how to construct the string with octal escape sequences.  BTDT in C.  was hoping there might be some defined way to do it that might end up running compiled C code at some internal point.  but i can just go ahead and construct it in Python code, to get it done.