need help understanding: converting text to binary

Eli the Bearded * at eli.users.panix.com
Tue Apr 23 16:51:31 EDT 2019


In comp.lang.python, Paul Rubin  <no.email at nospam.invalid> wrote:
> Eli the Bearded <*@eli.users.panix.com> writes:
>> # decode a single hex digit
>> def hord(c): ...
> 
>    def hord(c): return int(c, 16)

That's a good method, thanks.

> > # decode quoted printable, specifically the MIME-encoded words
> > # variant which is slightly different than the body text variant
> > def decodeqp(v): ...
> 
> I think this is supposed to mean:
> 
>     from itertools import islice
> 
>     def getbytes(v):
>         cs = iter(bytes(v,'ascii'))
>         for c in cs:
>             if c == ord('='):
>                 h1,h2 = islice(cs,2)
>                 yield int(chr(h1)+chr(h2), 16)
>             else: yield c
> 
>     def decodeqp(v):
>         return bytes(getbytes(v))
> 
>     print (decodeqp('=21_yes'))  # prints "b'!_yes'"

But that's not the output my sample produced.

      def getbytes(v):
          cs = iter(bytes(v,'ascii'))
          for c in cs:
              if c == ord('='):
                  h1,h2 = islice(cs,2)
                  yield int(chr(h1)+chr(h2), 16)
              elif c == ord('_'):
	          yield ord(' ')
              else: yield c

That's certainly a lot cleaner that what I had.

Elijah
------
and shorter than the one in /usr/lib/python3.5/quopri.py



More information about the Python-list mailing list