Python Forum

Full Version: Converting str to binary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

How can I iterate trough a phrase and convert each word to binary and then sum them? Is there a library/module for the alphabet/characteres?

For instance: mystring = 'My beautiful house'

binout = ' '.join('{0:08b}'.format(ord(x), 'b') for x in mystring)

1st_word = 01001101
...
last_word = 01100101
total_phrase = 1st_word + ... + last_word
TIA
I am not sure what means summation, may be string concatenation in this case.
Hope the following code helps you:

mystring = 'My beautiful house'

def word2bin(w):
    return '0b' + ''.join('{0:08b}'.format(ord(x), 'b') for x in w)

bin(sum(map(lambda x: int(x, 2), (word2bin(x) for x in mystring.split()))))