Python3中内置类型bytes和str用法及byte和string之间各种编码转换

本文介绍了Python3中bytes和str类型的使用方法及其之间的编码转换。详细解释了如何创建bytes类型的数据,并演示了如何通过不同编码方式(如UTF-8和GB2312)在字符串和字节串之间进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  Python3中内置类型bytesstr用法及bytestring之间各种编码转换

    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' # 字符串,编码

设置一个原始的字符串

>>> website  =  'http://www.169it.com/os'
>>>  type (website)
< class  'str' >
>>> website
'http://www.169it.com/os'
>>>

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

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

  gb2312的方式编码,转成bytes

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

   解码成string,默认不填

>>> website_string  =  website_bytes_utf8.decode()
>>>  type (website_string)
< class  'str' >
>>> website_string
'http://www.169it.com/os'
>>>
>>>

    解码成string,使用gb2312的方式

>>> website_string_gb2312  =  website_bytes_gb2312.decode( "gb2312" )
>>>  type (website_string_gb2312)
< class  'str' >
>>> website_string_gb2312
'http://www.169it.com/os'
>>>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值