Converting str to binary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Converting str to binary (/thread-19201.html) |
Converting str to binary - ebolisa - Jun-17-2019 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_wordTIA RE: Converting str to binary - scidam - Jun-17-2019 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())))) |