这是 python3 的异常,python2 中并无该异常

 

出现此类问题的场景如下:

1. 文件读取或写入,是否以 'b’ 二进制方式操作,显然这种方式为 byte

2. 网络编程,是否传输 二进制 字节

 

解决思路

str 通过 encode 方法编码为 byte

encode(self, encoding='utf-8', errors='strict')

或者通过 b'' 方法

 

byte 通过 decode 方法解码为 str

decode(self, *args, **kwargs)

 

示例

s1 = 'abc'
print(type(s1))      # <class 'str'>

s2 = s1.encode()
print(type(s2))     # <class 'bytes'>

s3 = s2.decode()
print(type(s3))     # <class 'str'>

s4 = b'123'
print(type(s4))     # <class 'bytes'>

 

 

 

参考资料:

相关文章:

  • 2022-01-14
  • 2022-01-10
  • 2022-01-07
  • 2022-12-23
  • 2021-06-08
  • 2021-12-23
  • 2022-12-23
  • 2021-07-21
猜你喜欢
  • 2021-07-13
  • 2021-12-10
  • 2022-02-01
  • 2022-01-03
相关资源
相似解决方案