Python Forum
convert a character to numeric and back
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
convert a character to numeric and back
#1
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?
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
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)
Reply
#3
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.
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
  Numeric Enigma Machine idev 8 129 2 hours ago
Last Post: idev
  Convert dataframe from str back to datafarme Creepy 1 584 Jul-07-2023, 02:13 PM
Last Post: snippsat
Question Numeric Anagrams - Count Occurances monty024 2 1,473 Nov-13-2021, 05:05 PM
Last Post: monty024
  How to get datetime from numeric format field klllmmm 3 1,957 Nov-06-2021, 03:26 PM
Last Post: snippsat
  [solved] unexpected character after line continuation character paul18fr 4 3,292 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  Extract continuous numeric characters from a string in Python Robotguy 2 2,580 Jan-16-2021, 12:44 AM
Last Post: snippsat
  SyntaxError: unexpected character after line continuation character siteshkumar 2 3,106 Jul-13-2020, 07:05 PM
Last Post: snippsat
  How to calculate column mean and row skip non numeric and na Mekala 5 4,831 May-06-2020, 10:52 AM
Last Post: anbu23
  How do I convert this string back to a list of integers? donmerch 6 3,652 Apr-05-2020, 06:43 PM
Last Post: donmerch
  Alpha numeric element list search rhubarbpieguy 1 1,740 Apr-01-2020, 12:41 PM
Last Post: pyzyx3qwerty

Forum Jump:

User Panel Messages

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