How to convert string to binary in Python?

PythonServer Side ProgrammingProgramming

To convert a string to binary, you need to iterate over each character and convert it to binary. Then join these characters together in a single string. You can use format(ord(x), 'b') to format the character x as binary. For example:

>>>st = "hello world"
>>>' '.join(format(ord(x), 'b') for x in st)
'11010001100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

 You can alsomap all characters to bin(number) using bytearray to get the array of allcharacters in binary. For example:

>>>st = "hello world"
>>>map(bin,bytearray(st))
['0b1101000','0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111','0b1101111', '0b1110010', '0b1101100', '0b1100100']
raja
Updated on 30-Sep-2019 07:29:16

Advertisements