How to convert string to binary in Python?

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"
['0b1101000','0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111','0b1101111', '0b1110010', '0b1101100', '0b1100100']