zerocool zerocool - 4 months ago 26
Python Question

convert decimal numbers to ascii

What would be the right way to convert set of decimal numbers into ASCII representation in Python? I have a bunch of lines like that:

99104101101115101
and if I manually separate these numbers to
'99 104 101 101 115 101'
then it will give
'cheese'
. Source data set have no spaces, no separators. Assume that the data only contains characters in a-z A-Z 0-9.

Answer
>>> import re
>>> re.sub('1?..', lambda m: chr(int(m.group())), '99104101101115101')
'cheese'

Demo with a random string of a million printable ASCII characters:

>>> import random
>>> original = ''.join(chr(random.randrange(32, 127)) for _ in range(1000000))
>>> len(original), original[:50]
(1000000, 'Ty-@u8ZJnh=`/Z*s,\\+@T PgZ/CE"Nq\\wXvqvDn`&)~BmP$n;f')

>>> encoded = ''.join(str(ord(c)) for c in original)
>>> len(encoded), encoded[:50]
(2284738, '84121456411756907411010461964790421154492436484328')

>>> decoded = re.sub('1?..', lambda m: chr(int(m.group())), encoded)
>>> decoded == original
True