zerocool zerocool - 1 year ago 124
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:

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

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

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(, encoded)
>>> decoded == original
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download