如何將字串轉換為Python中的二進位制數字?
要將字串轉換為二進位制數字,您需要遍歷每個字元並將其轉換為二進位制數字。然後將這些字元連線在一起,放入單個字串中。您可以使用 format(ord(x), 'b') 將字元 x 格式化為二進位制數字。例如
>>>st = "hello world" >>>' '.join(format(ord(x), 'b') for x in st) '11010001100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
您還可以使用位元組陣列將所有字元對映到 bin(number) 以獲取二進位制數字中的所有字元陣列。例如
>>>st = "hello world" >>>map(bin,bytearray(st)) ['0b1101000','0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111','0b1101111', '0b1110010', '0b1101100', '0b1100100']
廣告