str bytes如何转换

str        使用encode方法转换为bytes(爬虫的得到的响应以二进制的方式传送)

In [9]: a = "你好"                                                              

In [10]: type(a)                                                                
Out[10]: str

In [11]: b = a.encode()                                                         

In [12]: b                                                                      
Out[12]: b'\xe4\xbd\xa0\xe5\xa5\xbd'

In [13]: type(b)                                                                
Out[13]: bytes
bytes     通过decode转化为 str

In [12]: b                                                                      
Out[12]: b'\xe4\xbd\xa0\xe5\xa5\xbd'

In [13]: type(b)                                                                
Out[13]: bytes

In [14]: c = b.decode()                                                         

In [15]: c                                                                      
Out[15]: '你好'

In [16]: type(c)                                                                
Out[16]: str
默认方式都以utf-8的方式编解码。其编解码的方式必须一样,否则会出现乱码

In [17]: a = "你好"                                                             

In [18]: b = a.encode("gbk")                                                    

In [19]: b.decode()                                                             
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-19-4169e64150f6> in <module>
----> 1 b.decode()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte

In [20]: b.decode("gbk")                                                        
Out[20]: '你好'
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值