convert a character to numeric and back - 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: convert a character to numeric and back (/thread-24025.html) |
convert a character to numeric and back - Skaperen - Jan-28-2020 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? RE: convert a character to numeric and back - jfong - Jan-28-2020 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) RE: convert a character to numeric and back - Skaperen - Jan-28-2020 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. |