网络编程
位置:首页>> 网络编程>> Python编程>> Python常用类型转换实现代码实例

Python常用类型转换实现代码实例

作者:Mars.wang  发布时间:2022-05-20 06:03:43 

标签:python,类型,转换

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')

来源:https://www.cnblogs.com/wangbin2188/p/13186325.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com