Welcome, guest | Sign In | My Account | Store | Cart

String to binary snippet, python3+

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/usr/bin/python3
# Author: pantuts

binary = []
def strBin(s_str):
	for s in s_str:
	    if s == ' ':
	        binary.append('00100000')
	    else:
	        binary.append(bin(ord(s)))
s_str = input("String: ")
strBin(s_str)

b_str = '\n'.join(str(b_str) for b_str in binary) # print as type str
# replace '\n' to '' to output in one line without spaces, ' ' if with spaces

print(b_str.replace('b',''))

3 comments

Shawn 9 years, 1 month ago  # | flag

You can perform this conversion easily with a list comprehension and get a list of the binary representations.

>>> str2convert = "Hello world!"
>>> [ bin(ord(ch))[2:].zfill(8) for ch in str2convert ]
['01001000', '01100101', '01101100', '01101100', '01101111', '00100000', '01110111', '01101111', '01110010', '01101100', '01100100', '00100001']

You can then assign the list to a variable, or directly loop over the list comprehension to print it.

This technique will work in Python 2.6+.

Note that there is no need to special case the space character. ord() does the right thing:

>>> ord(' ')
32
>>> 0b00100000
32
>>>

Here is a little more information to illustrate what is happening to each character of the string inside the list comprehension:

>>> ord('A')
65
>>> bin(ord('A'))  # Provide a string with the binary representation of the number returned by ord()
'0b1000001'
>>> bin(ord('A'))[2:]  # A string is a list, so we can use slicing to "carve off" the leading '0b'
'1000001'
>>> bin(ord('A'))[2:].zfill(8)  # If we want a fixed 8-bits to represent each character's binary value, we can pad the front of the string with zeroes
'01000001'
p@ntut$ (author) 9 years, 1 month ago  # | flag

Cool list compreshension. Thanks man!

aa2zz6 6 years, 9 months ago  # | flag

a = "text here" a_bytes = bytes(a, "ascii") print(''.join(["{0:b}".format(x) for x in a_bytes]))

Created by p@ntut$ on Wed, 17 Oct 2012 (GPL3)
Python recipes (4591)
p@ntut$'s recipes (7)

Required Modules

  • (none specified)

Other Information and Tasks

  • Licensed under the GPL 3
  • Viewed 47658 times
  • Revision 2 (updated 7 years ago)