str-bytes

PS: 这个坑踩了无数遍,填了它😀😜😜

python-字节型数据与字符串的转换

bytes to str

  • str(bytes, encoding="utf-8")

      In [4]: type(b)  
      Out[4]: bytes  
    
      In [7]: c = str(b, encoding="utf-8")  
    
      In [8]: type(c)  
      Out[8]: str  
  • bytes.decode(bytes)

      In [14]: type(z)  
      Out[14]: bytes  
    
      In [15]: m = bytes.decode(z)  
    
      In [16]: type(m)  
      Out[16]: str  
  • repr(bytes)

      In [7]: a = b"12345"   
    
      In [8]: type(a)   
      Out[8]: bytes   
    
      In [9]: b = repr(a)   
    
      In [10]: type(b)   
      Out[10]: str   
    
      In [11]: print(b)   
      b'12345'   

str to bytes

  • bytes(string, encoding='utf-8')

      In [2]: type(a)  
      Out[2]: str  
    
      In [3]: b = bytes(a, encoding="utf-8")  
    
      In [4]: type(b)  
      Out[4]: bytes  
  • str.encode(str)

      In [13]: type(a)  
      Out[13]: str  
    
      In [12]: z = str.encode(a)  
    
      In [14]: type(z)  
      Out[14]: bytes