Python Forum
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
octal instead of hex
#1
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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.
Reply
#3
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]
Reply
#4
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  regex octal replace chaz_sliger 1 2,877 Sep-06-2018, 01:21 AM
Last Post: scidam
  octal encoding Skaperen 4 3,888 Dec-06-2017, 02:53 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020