I have a function that converts characters to binary
def binary(value):
return ''.join(format(ord(i), 'b') for i in value)
print(binary('a')) # 1100001
print(binary('b')) # 1100010
But when I give multiple characters, they are joined together
print(binary('ab')) # 11000011100010
I want to find a way to split these apart into the individual letters. E.g.
'11000011100010' -> '1100001 1100010'
CodePudding user response:
The best way is to store all the generated binaries in a list then join all the items.
output=[]
def binary(a):
binary = ''.join(format(ord(i), '08b') for i in a)
#print(binary)
output.append(binary)
def split_string(a):
for i in a:
binary(i)
split_string('ram')
print("output: ", ' '.join(map(str,output)))
you will get the output like below.
output: 01110010 01100001 01101101
CodePudding user response:
You lose any spacing information with ''.join
. Instead, format each character, then join later.
def binary(value):
for c in value:
yield format(ord(c), 'b')
print(' '.join([x for x in binary('ab')]))
# '1100001 1100010'
CodePudding user response:
Your binary sequences have a length that's the number of bits required to just represent the number (happens to be 7 in both cases here) - but they could be very different lengths. You are throwing that information away in your ''.join() call and there's no way to retrieve that. Why not return a list of strings, instead of concatenating them all?
I.e:
# when passed value='ab', this will compute the binary representation of 'a'
# and then 'b', both 7 bits, and combine them into a single string of bits,
# 14 characters long; however the fact that these strings were both 7
# characters long gets lost (could have been 6 8, 8 6, etc.)
def binary(value):
return ''.join(format(ord(i), 'b') for i in value)
print(binary('ab')) # prints all 14 characters
So, if you instead:
def binary(value):
return [format(ord(i), 'b') for i in value]
print(binary('ab'))
The result is:
['1100001', '1100010']
You can work with those like this:
bs = binary('ab')
print(bs[0])
print(bs[1])
print(''.join(bs))
Result:
1100001
1100010
11000011100010
If, for example, you just want a space between each block:
print(' '.join(bs))
Result:
1100001 1100010
Padding to 8-bit words:
print(' '.join(b.zfill(8) for b in bs))
Result:
01100001 01100010
However, be careful with something like bs = binary('课题')
.