加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

python3 中 bytes 与 string 的互相转换

发布时间:2021-07-06 05:59:34 所属栏目:大数据 来源: https://blog.csdn.net/yilovex
导读:首先来设置一个原始的字符串, Python 3.2.3 (default,Apr 11 2012,07:15:24) [MSC v.1500 32 bit (Intel)] on win32Type "help","copyright","credits" or "license" for more information. website = 'http://www.cnblogs.com/txw1958/' type(website)clas

首先来设置一个原始的字符串,

Python 3.2.3 (default,Apr 11 2012,07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "help","copyright","credits" or "license" for more information.
>>> website = 'http://www.cnblogs.com/txw1958/'
>>> type(website)
<class 'str'>
>>> website
'http://www.cnblogs.com/txw1958/'
>>>

?

按utf-8的方式编码,转成bytes

>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)
<class 'bytes'>
>>> website_bytes_utf8
b'http://www.cnblogs.com/txw1958/'
>>>

?

按gb2312的方式编码,转成bytes

>>> website_bytes_gb2312 = website.encode(encoding="gb2312")
>>> type(website_bytes_gb2312)
<class 'bytes'>
>>> website_bytes_gb2312
b'http://www.cnblogs.com/txw1958/'
>>>

?

解码成string,默认不填

>>> website_string = website_bytes_utf8.decode()
>>> type(website_string)
<class 'str'>
>>> website_string
'http://www.cnblogs.com/txw1958/'
>>>
>>>

?

解码成string,使用gb2312的方式

>>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")
>>> type(website_string_gb2312)
<class 'str'>
>>> website_string_gb2312
'http://www.cnblogs.com/txw1958/'
>>>

?

版权声明:本文为方倍工作室原创文章,未经授权不得转载。 https://blog.csdn.net/txw1958/article/details/9425041

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读