在Python中,如何將一個字符串轉換為相應的二進制串(01形式表示),並且能夠將這個二進制串再轉換回原來的字符串。
# 編碼:轉成相應的二進制串
def encode(s): return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
#解碼:將二進制字符串轉換為原來的字符串 def decode(s): return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])
例如:
>>>encode('hello') '1101000 1100101 1101100 1101100 1101111' >>>decode('1101000 1100101 1101100 1101100 1101111') 'hello'