Python Forum

Full Version: convert a character to numeric and back
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
if my function gets a single character that is str or bytes or bytearray, there is a simple way to convert its character code. ord() works for all 5 types, so thats easy. going the other way has to be harder because of which type you want to go to. chr() get str.

i want the same type as i originally had because this conversion is because i need to do changes to the character that are done as a numeric code. Unicode is not involved. all characters are ASCII only even for type str.

what's a good way to convert back to the original character type?
The type info is lost after ord(). Can't get it back unless store it first.

t = type(c)
n = ord(c)
...later
try:
    t(chr(n), encoding='utf8')
except TypeError:
    chr(n)
i still have the original value that was passed to ord(). or i could to t=type() as your code starts with.

unfortunately, the bytes() and bytearray() types as functions don't convert number the the ASCII character with that code. and if you use encoding= it expects a string argument (try it).

it looks like i'll need to do:
n=ord(c)
n=...n...
if t is str:
    return chr(n)
if t in (bytes,bytearray):
    return t([n])
that's not bad.