Python常用类型转换实现

Python常用类型转换实现,第1张

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

推荐教程:《Python教程》

以上就是Python常用类型转换实现的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/682678.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存