1.字符串转成bytes:str.encode('utf-8')
示例1:
>>>'abc'.encode('utf-8')
>>>b'abc'
>>>'123abc'.encode('utf-8')
>>>b'123abc'
>>>'我爱python'.encode('utf-8')
>>>b'\xe6\x88\x91\xe7\x88\xb1python'
2.bytes转成字符串:bytes.decode('utf-8')
示例2:
>>>b'abc'.decode('utf-8')
>>>abc
>>>b'\xe6\x88\x91\xe7\x88\xb1python'.decode('utf-8')
>>>'我爱python'
本文详细介绍了Python中字符串与bytes类型之间的转换方法。通过示例演示了如何使用str.encode('utf-8')将字符串转换为bytes,以及如何使用bytes.decode('utf-8')将bytes转换回字符串。

323

被折叠的 条评论
为什么被折叠?



