Python 2.5 convert string to binary

后端 未结 2 1865
闹比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.

提交回复
热议问题