
我们在Python中会遇到很多转换的问题,例如需要字符串,而输入内容为二进制。码的是字符串,却要是字符串。字符串与二进制如何相互转换呢?本文向大家介绍Python中字符串与二进制相互转换的两种方法,一个是简单版本,另一个是依靠bitarray对象,也是可以轻松转化。内容如下:
简单版本
1 2 3 4 5 6 7 8 9 10 | 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'
|
bitarray法
将二进制串转化为bitarray对象,bitarray对象可以轻松转化为bytes
1 2 3 4 5 6 7 8 9 10 | from bitarray import bitarray
def str2bitarray(s):
ret = bitarray( '' .join([bin(int( '1' + hex(c)[2:], 16))[3:] for c in s.encode( 'utf-8' )]))
return ret
def bitarray2str(bit):
return bit.tobytes().decode( 'utf-8' )
|
以上就是Python中字符串与二进制相互转换的两种方法,你学会了吗?大家可以直接套用上面的代码哦~