标签:utf 字节 python bytes print world hello
python的字节串
本文环境为python3.7
认识字节串
字节串,也叫字节序列(bytes),用来存储以字节为单位的数据。
创建空的字节串
>>> string=b''
>>> type(string)
<class 'bytes'>
>>> string=b""
>>> type(string)
<class 'bytes'>
可以看到string的类型为bytes
创建非空的字节串
>>> string1=b'hello world'
>>> type(string1)
<class 'bytes'>
>>> string2=b'\x62\x71'
>>> type(string2)
<class 'bytes'>
可以看到字节串的典型特征为 b'this is a bytes'
,以b为前缀。
字节串与字符串的相互转化
string1 = "hello world" # this is str
string2 = b"hello world" # this is bytes
print('change str into bytes')
print(bytes(string1, encoding='utf-8'))
print(str.encode(string1)) # 默认编码方式就是utf-8
print(string1.encode('utf-8')) # 默认编码方式就是utf-8,可以直接写成string1.encode()
print('--------------')
print('change bytes into str')
print(str(string2, encoding='utf-8'))
print(bytes.decode(string2)) # 默认解码方式就是utf-8
print(string2.decode('utf-8')) # 默认解码方式就是utf-8,可以直接写成string2.decode()
运行结果:
change str into bytes
b'hello world'
b'hello world'
b'hello world'
--------------
change bytes into str
hello world
hello world
hello world
标签:utf,字节,python,bytes,print,world,hello 来源: https://www.cnblogs.com/jackie-lee/p/16503114.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。