Python Forum
octal instead of hex - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: octal instead of hex (/thread-3580.html)



octal instead of hex - Skaperen - Jun-05-2017

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.


RE: octal instead of hex - rrashkin - Jun-05-2017

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.


RE: octal instead of hex - Larz60+ - Jun-05-2017

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]



RE: octal instead of hex - wavic - Jun-05-2017

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


RE: octal instead of hex - Skaperen - Jun-06-2017

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.