1.byte與str互轉
b = b"example" s = "example" bytes(s, encoding = "utf8") str(b, encoding = "utf-8")
2.byte與int互轉
b=b'\x01\x02' num=int.from_bytes(b,'little') b1=num.to_bytes(2,'little')
3.byte和float互轉
#import struct s=b'@zQ\x16' def byteToFloat(b): return struct.unpack('!f',s)[0] def floatToBytes(f): bs = struct.pack("f",f) return bytes((bs[3],bs[2],bs[1],bs[0])) f1=byteToFloat(s) floatToBytes(f1)
4.str和bytearray互相轉
#str1='aaabb' ba=bytearray(str1,encoding='utf-8') str2=ba.decode('utf8')
推薦教學:《Python教學》
以上是Python常用型別轉換實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!