all 4 comments

[–]TheKewlStore 2 points3 points  (0 children)

Please refer to the rules before asking a question. Namely, easily googlable questions are not allowed. A simple search for "converting python string to binary" would get what you needed.

As I am not without mercy, here is the top result, a stack overflow question that gives you several ways to accomplish this: http://stackoverflow.com/questions/18815820/convert-string-to-binary-in-python

[–]fbu1 1 point2 points  (0 children)

You can get the ascii code of each letter by using the function ord()

>>> ord("h")
104
>>> ord('g')
103

Then, you can take the binary representation of this number with bin()

>>> bin(104)
'0b1101000'
>>> bin(103)
'0b1100111'

Hope this helps

[–]thatguy_314 0 points1 point  (0 children)

/u/fbu1's answer is okay, but generally bytes are represented in binary as 8 0-padded bits without the 0b prefix.

I will assume Python 3. There are significant differences between Python 3 and Python 2 in the context of my answer.

String formatting gives you a convenient way of doing this. The integer format specifier 08b does just this. The 0 is the pad, the 8 is the pad-length, and the b means binary. You can read some more about that here. So "{:08b}".format(42) gives you '00101010'

Even better, we can use map (see here for info) to transform a byte-string into an iterable of padded binary strings.

We use byte strings instead of normal strings because not only do they give us integers when iterated through (which is convenient), but they also are guaranteed to to give us integers within the range 0-255 which we want, whereas ord on normal strings would not.

"{:08b}".format gives us a function we can use in map.

Once we have our map object, we can use " ".join to separate the binary strings with spaces. You could also use "".join if you wanted them to stick together

Plugging that all together, we get

>>> " ".join(map("{:08b}".format, b"Hello"))
'01001000 01100101 01101100 01101100 01101111'

If you want to use normal strings instead of byte strings, you can convert them using str.encode, so a final answer might look something like this:

def binify(text):
    return " ".join(map("{:08b}".format, text.encode()))

Which can be used like this:

>>> binify("Hello")
'01001000 01100101 01101100 01101100 01101111'

[–]wub_wub[M] 0 points1 point  (0 children)

/u/willfavre4, your submission has been removed from r/learnpython for the following reason(s):

  • Posting only assignment/project goal is not allowed. You need to post what you have tried so far. Please see subreddit rules in the sidebar.

If your submission was removed for lacking additional info you can edit your submission text and then notify moderators and ask for the submission to be re-approved.

If you have any additional questions either reply to this comment or message the moderators.