String to binary snippet, python3+
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',''))
|
You can perform this conversion easily with a list comprehension and get a list of the binary representations.
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:Here is a little more information to illustrate what is happening to each character of the string inside the list comprehension:
Cool list compreshension. Thanks man!
a = "text here" a_bytes = bytes(a, "ascii") print(''.join(["{0:b}".format(x) for x in a_bytes]))