如何编写Python中常用类型转换的代码示例?

2026-05-21 22:183阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计221个文字,预计阅读时间需要1分钟。

如何编写Python中常用类型转换的代码示例?

1. byte和str互转pythonb=bexamples=examplebytes_s=bytes(s, encoding=utf-8)str_b=str(b, encoding=utf-8)

2. byte和int互转pythonb=b'\x01\x02'num=int.from_bytes(b, 'little')b1=num.to_bytes(2, 'little')

3. byte和float互转pythonimport structb=b'\x00\x00\x00\x00\x00\x00\x00\x16'num=struct.unpack('d', b)[0]b1=struct.pack('d', num)

1.byte和str互转

b = b"example"
s = "example"
bytes(s, encoding = "utf8")
str(b, encoding = "utf-8")

如何编写Python中常用类型转换的代码示例?

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计221个文字,预计阅读时间需要1分钟。

如何编写Python中常用类型转换的代码示例?

1. byte和str互转pythonb=bexamples=examplebytes_s=bytes(s, encoding=utf-8)str_b=str(b, encoding=utf-8)

2. byte和int互转pythonb=b'\x01\x02'num=int.from_bytes(b, 'little')b1=num.to_bytes(2, 'little')

3. byte和float互转pythonimport structb=b'\x00\x00\x00\x00\x00\x00\x00\x16'num=struct.unpack('d', b)[0]b1=struct.pack('d', num)

1.byte和str互转

b = b"example"
s = "example"
bytes(s, encoding = "utf8")
str(b, encoding = "utf-8")

如何编写Python中常用类型转换的代码示例?

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。