python bytes和string相互转换(46)
一.bytes和string区别
1.python bytes 也称字节序列,并非字符。取值范围 0 <= bytes <= 255,输出的时候最前面会有字符b修饰;string 是python中字符串类型;
2.bytes主要是给在计算机看的,string主要是给人看的;
3.string经过编码encode,转化成二进制对象,给计算机识别;bytes经过解码decode,转化成string,让我们看,但是注意反编码的编码规则是有范围,\xc8就不是utf8识别的范围;
if __name__ == "__main__": # 字节对象b b = b"shuopython.com" # 字符串对象s s = "shuopython.com" print(b) print(type(b)) print(s) print(type(s))
输出结果:
b‘shuopython.com‘ <class ‘bytes‘> shuopython.com <class ‘str‘>
二.bytes转string
string经过编码encode转化成bytes
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:何以解忧 @Blog(个人博客地址): shuopython.com @WeChat Official Account(微信公众号):猿说python @Github:www.github.com @File:python_bytes_string.py @Time:2020/2/26 21:25 @Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累! """ if __name__ == "__main__": s = "shuopython.com" # 将字符串转换为字节对象 b2 = bytes(s, encoding=‘utf8‘) # 必须制定编码格式 # print(b2) # 字符串encode将获得一个bytes对象 b3 = str.encode(s) b4 = s.encode() print(b3) print(type(b3)) print(b4) print(type(b4))
输出结果:
b‘shuopython.com‘ <class ‘bytes‘> b‘shuopython.com‘ <class ‘bytes‘>
三.string转bytes
bytes经过解码decode转化成string
if __name__ == "__main__": # 字节对象b b = b"shuopython.com" print(b) b = bytes("猿说python", encoding=‘utf8‘) print(b) s2 = bytes.decode(b) s3 = b.decode() print(s2) print(s3)
输出结果:
b‘shuopython.com‘ b‘\xe7\x8c\xbf\xe8\xaf\xb4python‘ 猿说python 猿说python
猜你喜欢:
转载请注明:猿说Python » python bytes和string相互转换
技术交流、商务合作请直接联系博主
扫码或搜索:猿说python
猿说python
微信公众号 扫一扫关注
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25