前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3将API返回的bytes解码为str

Python3将API返回的bytes解码为str

作者头像
十里桃花舞丶
发布2019-02-20 15:55:01
8050
发布2019-02-20 15:55:01
举报
文章被收录于专栏:桥路_大数据桥路_大数据

前言

在调用API的时候,有些API会返回bytes类型的串,格式如下:

代码语言:javascript
复制
b'{"status":"0","msg":"ok","result":{"type":"google","from":"zh-cn","to":"en","text":"\xe4\xb8\xad\xe5\x9b\xbd",
"result":"China<br \\/><br \\/><strong>\xe5\x90\x8d\xe8\xaf\x8d<\\/strong><br \\/><span class=\\"green\\">China<\\/span> 
\xe4\xb8\xad\xe5\x9b\xbd, \xe5\x8d\x8e, \xe4\xb8\xad\xe5\x8d\x8e<br \\/>"}}'

如果将这种类型的字串直接存入到数据库的话,从数据库中读取出的字串进行操作会出现问题,比如上面的字串直接进行解析的话会直接报错,原因是str存着的实际上是一串没有解码的bytes。所以存入数据库时,要对bytes进行解码的操作。各位看官,详细操作请往下看。

bytes解码

代码语言:javascript
复制
bytes.decode(encoding='utf-8')

注:bytes为要解码的bytes串

bytes编码

代码语言:javascript
复制
S.encode(encoding='utf-8', errors='strict') -> bytes

注:S为str

源码

代码语言:javascript
复制
def decode(self, *args, **kwargs): # real signature unknown
    """
    Decode the bytes using the codec registered for encoding.
    
      encoding
        The encoding with which to decode the bytes.
      errors
        The error handling scheme to use for the handling of decoding errors.
        The default is 'strict' meaning that decoding errors raise a
        UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that
        can handle UnicodeDecodeErrors.
    """
    pass
代码语言:javascript
复制
def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
    """
    S.encode(encoding='utf-8', errors='strict') -> bytes
    
    Encode S using the codec registered for encoding. Default encoding
    is 'utf-8'. errors may be given to set a different error
    handling scheme. Default is 'strict' meaning that encoding errors raise
    a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
    'xmlcharrefreplace' as well as any other name registered with
    codecs.register_error that can handle UnicodeEncodeErrors.
    """
    return b""
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年03月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • bytes解码
  • bytes编码
  • 源码
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档