Skip to content Skip to sidebar Skip to footer

Python 2.5 Convert 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 usin

Solution 1:

This one-line works:

>>> ''.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'

Solution 2:

I think you could do it in a cleaner way like this:

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

the format function will represent the character in a 8 digits, binary representation.


Post a Comment for "Python 2.5 Convert String To Binary"