python从bytes转到str转码输出问题

发布于 2020-09-08  310 次阅读



abbrlink: ba256ea6
title: python从bytes转到str转码输出问题
related_posts: true
comments: true
copyright: true
top:
date: 2020-04-23 10:55:42
updated:
type:
tags: Python
categories: Python
password:

python从bytes转到str转码输出问题

python从bytes转到str

使用以下代码测试urllib库的urlopen()方法时,发现输出的为bytes类型:

import urllib.request

if __name__ == "__main__":
    data = bytes(urllib.parse.urlencode({'word': 'hello GanAH'}), encoding='UTF-8')
    respose2 = urllib.request.urlopen("http://httpbin.org/post", data=data)

    print((respose2.read()))

比较长,影响阅读分析

对结果转码输出:.decode('utf-8')

源代码中更改如下:

  print((respose2.read()).decode('utf-8'))
更改后的输出结果:

如需要回转则decode改成encode即可。

更多内容请关注: