-1

Got a string in ASCII (with only ASCII value ranges for A-Z, a-z, and " "), want to decode it.

ex. "781059910132" cooresponds to "Nice "

Is there an easy way to do this in Python 3?

SS'
  • 819
  • 1
  • 8
  • 18
  • 6
    I doubt there's an unambiguous way to do this. You can't tell just by looking at the number sequence that it should be interpreted as [78, 105, 99, ...]. It could just as easily be [78, 10, 59, 91, ...]. – Kevin Aug 28 '18 at 18:23
  • Should have mentioned that my ASCII values are only for specific ranges. A-Z, 65-90, a-z, 97-122 and 32 respectively – SS' Aug 28 '18 at 18:28
  • I can think of an approach with looping with these restrictions but was wondering if there was a more pythonic way – SS' Aug 28 '18 at 18:28
  • 1
    Oh, in that case maybe there _is_ an unambiguous solution, since when you encounter a "1" then it can only mean you're about to encounter a three digit number. – Kevin Aug 28 '18 at 18:30

1 Answers1

2

You can use regular expressions to extract 3- or 2-digit combinations:

import re
ascii_char = '[01]?\d\d'
s = '781059910132'
''.join(map(chr, map(int, re.findall(ascii_char, s))))
#'Nice '

This code works even with 0-padded codes:

''.join(map(chr, map(int, re.findall(ascii_char, '07832078'))))
#'N N'
DYZ
  • 55,249
  • 10
  • 64
  • 93