On Wed, Sep 12, 2012 at 7:20 AM, Aaron Pilgrim <aaron...@gmail.com> wrote: > Hello, > I am trying to write a small program that converts ascii to binary. > > I tried using the python reference library section 18.8 but had > trouble understanding how to make it work. > > Here is the code I am currently trying to use: > > def main(): > import binascii > myWord = input("Enter the word to convert..") > #convert text to ascii > for ch in myWord: > print(ord(ch)) > #convert ascii to binary > binascii.a2b_uu(ord(ch))
I'm not sure what you want, based on the code above. uuencoding is meant for sending data through 7-bit channels like email and newsgroups. For example: >>> binascii.b2a_uu('\x81\x82') # 8-bit binary to 7-bit ascii '"@8( \n' >>> binascii.a2b_uu('"@8( \n') # 7-bit ascii back to 8-bit '\x81\x82' http://docs.python.org/py3k/library/binascii.html#binascii.a2b_uu Do you instead want an ASCII bitstring (i.e. 1s and 0s)? These will raise a UnicodeError if the string isn't ASCII. # Python 3 def iter_bin(s): sb = s.encode('ascii') return (format(b, '07b') for b in sb) # Python 2 def iter_bin(s): sb = s.encode('ascii') return (format(ord(b), '07b') for b in sb) For example: >>> for s in iter_bin("Spam"): ... print(s) ... 1010011 1110000 1100001 1101101 >>> print(*iter_bin("Spam"), sep='') # Python 3 1010011111000011000011101101 >>> print ''.join(s for s in iter_bin("Spam")) # Python 2 1010011111000011000011101101 _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor