Python 2.5 converts a string to binary

I know this is easily possible in python 2.6. But what is the easiest way to do this in Python 2.5?

x = "This is my string" b = to_bytes(x) # I could do this easily in 2.7 using bin/ord 3+ could use b"my string" print b 

Any suggestions? I want to take x and turn it into

001000100101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010101011001001101001011011100110011100100010

+3
python
Dec 18 '11 at 17:06
source share
2 answers

This one line job:

 >>> ''.join(['%08d'%int(bin(ord(i))[2:]) for i in 'This is my string']) '0101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010001110010011010010110111001100111' 

EDIT

You can write bin() yourself

 def bin(x): if x==0: return '0' else: return (bin(x/2)+str(x%2)).lstrip('0') or '0' 
+6
Jan 10 2018-12-01T00:
source share

I think you could make it cleaner like this:

 >>>''.join(format(ord(c), '08b') for c in 'This is my string') '0101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010001110010011010010110111001100111' 

the format function will represent the character in an 8-digit binary representation.

0
Sep 26 '13 at 9:21
source share



All Articles