一.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(个人博客地址): https://www.codersrc.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"https://www.codersrc.com/"
print(b)
b = bytes("猿说python", encoding='utf8')
print(b)
s2 = bytes.decode(b)
s3 = b.decode()
print(s2)
print(s3)
输出结果:
b'https://www.codersrc.com/'
b'\xe7\x8c\xbf\xe8\xaf\xb4python'
猿说python
猿说python