python中bytes类型转换为str类型

使用的原因:基于URL解析报文的时候,要使用str类型,但是提供的确实bytes类型,报错:

TypeError: must be str, not bytes

所以就把bytes类型转换为str类型汇总下,以便日后查看
bytes1 = b'Hello my world'
str1 = 'Hello my world'
print(type(bytes1))
print(type(s1))

# bytes类型转换为str类型
# 方法1: str()函数
str2 = str(bytes1, encoding="utf-8")
print(str2)
print(type(str2))

# 方法2: bytes.decode()函数
str3 = bytes.decode(bytes1)
print(str3)
print(type(str3))
结论,通过两种发杠均可将bytes转换为str:
<class 'bytes'>
<class 'str'>
Hello my world
<class 'str'>
Hello my world
<class 'str'>

转载于:https://www.cnblogs.com/pinpin/p/10412421.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值