Encode string as octal utf-8 Python 3

Viewed 1920

Is there a good way to encode strings to utf-8, but in octal format instead of the default hexadecimal?

For example:

>>> "õ".encode("utf-8")
b'\xc3\xb5'

Here the output is hex, not octal. The output in octal would be: b'\303\265'

Python 3 automatically handles the decoding just fine:

>>> b"\xc3\xb5".decode("utf-8")
'õ'
>>> b'\303\265'.decode("utf-8")
'õ'

Is there a codec or option I'm missing? I'd like to avoid a lot of manual string manipulation.

update: I had misunderstood -- there is no difference between b"\xc3\xb5" and b'\303\265' at all, rather they are just 2 different ways to display the same underlying byte code. In fact:

>>> b"\xc3\xb5" == b'\303\265'
True
3 Answers

Here's a class that overrides the representation of the string it wraps:

>>> class OctUTF8:
...   def __init__(self,s):
...     self.s = s.encode()
...   def __repr__(self):
...     return "b'" + ''.join(f'\\{n:03o}' for n in self.s) + "'"
...
>>> s='õ'
>>> OctUTF8(s)
b'\303\265'

This representation can be evaluated as a byte string and decoded back to the original:

>>> eval(repr(OctUTF8(s))).decode()
'õ'

First, you can use ord() to convert a character in a string
to it's Unicode form, then, you can use oct():

print(oct(ord("õ")))

Output:

0o365

You can convert each byte in a bytes object to it's octal representation

[oct(b) for b in "õ".encode("utf-8")]

Gives

['0o303', '0o265']

You can manipulate the results to convert it to your desired output

Related