在python2中用urllib模块去请求淘宝的IP地址查询接口,返回的是一段json字符串,如下所示:
import urllib
def get_data(ip):
url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip
data = urllib.urlopen(url).read()
return data
if __name__ == "__main__":
result = get_data("59.151.5.5")
print(result)
返回结果如下:
{"code":0,"data":{"country":"\u4e2d\u56fd","country_id":"CN","area":"\u534e\u5317","area_id":"100000","region":"\u5317\u4eac\u5e02","region_id":"110000","city":"\u5317\u4eac\u5e02","city_id":"110100","county":"","county_id":"-1","isp":"\u4e16\u7eaa\u4e92\u8054","isp_id":"100021","ip":"59.151.5.5"}}
在返回结果中,中文是以 unicode字符串表示,这样不方便阅读,我想让结果中中文部分直接用中文表示,就像下面这样:
"city":"北京","ISP":"中国电信"
如果是python3的话返回又是这样的:
b'{"code":0,"data":{"country":"\\u4e2d\\u56fd","country_id":"CN","area":"\\u534e\\u5317","area_id":"100000","region":"\\u5317\\u4eac\\u5e02","region_id":"110000","city":"\\u5317\\u4eac\\u5e02","city_id":"110100","county":"","county_id":"-1","isp":"\\u4e16\\u7eaa\\u4e92\\u8054","isp_id":"100021","ip":"59.151.5.5"}}'
请问在 python2和python3中分别该如何转码呢?
Python3中有兩個方法可以解決你的問題:
print()函數
Python3開始編碼定義為UTF-8,所以你懂的,直接印就行:
利用Unicode資料庫
有個自帶的函式庫
unicodedata
,可以呼叫這個函式庫中的兩個方法,如下:補充一下,如果單獨處理字元可以用上面的方法,但是剛剛回答完才發現你的返回值為byte對象,Python3中這種對象處理很簡單,修改你的程式碼如下:
我測試完的回傳值是:
希望採納
Python 3裡你可以用decode方法把bytes轉換str:
這樣就好了==
請使用py3