python字符串、字节串,转码

1、参考:https://www.jianshu.com/p/5bb986772ef8

https://www.cnblogs.com/longyuu/p/14180127.html

2、示例

t1 = 'test'.encode()
type(t1)
# <class 'bytes'>

t2 = b'test'.decode()
type(t2)
# <class 'str'>

t3 = b'test'.hex()
type(t3)
# <class 'str'>

my_hex = '\x53\x00\x45\x00\x54\x00\x41\x00\x42\x00\x4c\x00\x45\x00\x20\x00\x4f\x00\x4e\x00'
type(my_hex)
# <class 'str'>

t4 = "\\".join(hex(ord(n)) for n in my_hex)
type(t4)
# <class 'str'>

t5 = bytes([ord(n) for n in my_hex])
type(t5)
# <class 'bytes'>

t6 = t5.decode('utf-16')
print(t6)
# SETABLE ON

3、示例2

soc_bytes= bytearray()
soc_bytes.append(0x1C)
soc_bytes.append(0x03)
soc_bytes.append(0x09)

soc = " ".join(hex(n) for n in soc_bytes)
soc1 = " ".join(f"{n:02x}" for n in soc_bytes)
print(f"发送消息: {soc}")
print(f"发送消息1: {soc1}")

print(":".join(hex(n) for n in b"TCB"))
print(":".join(f"{n:02X}" for n in b"TCB"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值