python内置函数bytes返回一个新的bytes类型的对象,bytes类型对象是不可变序列,包含范围为 0 <= x < 256 的整数。bytes可以看做是bytearray的不可变版本,它同样支持索引和切片操作 bytes语法 class bytes([source[, encoding[, errors]]])
语法结构:
class bytes([source[, encoding[, errors]]])
参数解释:
示例代码1:
print(bytes())
print(bytes("I love python", encoding='utf-8'))
print(bytes(6))
print(bytes([11, 22, 33]))
运行结果:
示例代码2:
s = 'I love python!'
print(s)
a = s.encode(encoding='utf-8')
print(a)
b = bytes(s, encoding='utf-8')
print(b)
c = a.decode('utf-8')
print(c)
d = b.decode('utf-8')
print(d)
运行结果:
示例代码3:
int_6 = bytes([6])
print(int_6)
bytes_to_int = int.from_bytes(int_6, 'little')
# bytes_to_int = int.from_bytes(int_6, 'big')
print(bytes_to_int)
int_66 = bytes([66])
print(int_66)
bytes_to_int = int.from_bytes(int_66, 'little')
# bytes_to_int = int.from_bytes(int_66, 'big')
print(bytes_to_int)
运行结果: