Python 2.5 convert string to binary

后端 未结 2 1832
闹比i
闹比i 2021-01-06 06:03

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 d         


        
相关标签:
2条回答
  • 2021-01-06 06:35

    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.

    0 讨论(0)
  • 2021-01-06 06:49

    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'
    
    0 讨论(0)
提交回复
热议问题