python3中bytes和string之间的互相转换

yipeiwu_com5年前Python基础

前言

Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式混用str和bytes,正是这使得两者的区分特别清晰。你不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也不能将字符串传入参数为字节包的函数(反之亦然).

python3.0中怎么创建bytes型数据

bytes([1,2,3,4,5,6,7,8,9])
bytes("python", 'ascii') # 字符串,编码

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

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 = '//www.jb51.net/'
>>> type(website)
<class 'str'>
>>> website
'//www.jb51.net/'
>>>

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

>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)
<class 'bytes'>
>>> website_bytes_utf8
b'//www.jb51.net/'
>>>

按gb2312的方式编码,转成bytes

>>> website_bytes_gb2312 = website.encode(encoding="gb2312")
>>> type(website_bytes_gb2312)
<class 'bytes'>
>>> website_bytes_gb2312
b'//www.jb51.net/'
>>>

解码成string,默认不填

>>> website_string = website_bytes_utf8.decode()
>>> type(website_string)
<class 'str'>
>>> website_string
'//www.jb51.net/'
>>>
>>>

解码成string,使用gb2312的方式

>>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")
>>> type(website_string_gb2312)
<class 'str'>
>>> website_string_gb2312
'//www.jb51.net/'
>>>

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

python代码过长的换行方法

python代码换行就是每行后面加个 \ 举个栗子: time = "2017" print "one" + "," \ + "two" \ + ",three" + \ "," +...

Python字符串格式化输出代码实例

这篇文章主要介绍了Python字符串格式化输出代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用占位符%s name...

python中abs&map&reduce简介

abs函数 可以把函数本身赋值给变量 >>> f = abs 变量可以指向函数 >>> f = abs >>> f(-10) 10...

python 中random模块的常用方法总结

python 中random的常用方法总结 一、random常用模块 1.random.random() 随机生成一个小数 print(random.random()) # 输出...

利用Python模拟登录pastebin.com的实现方法

利用Python模拟登录pastebin.com的实现方法

任务 在https://pastebin.com/网站注册一个账号,利用python实现用户的自动登录和创建paste。该任务需要分成如下两步利用python实现: 1.账号的自动登录...