目录
- 一.Python bytes 和 string 区别
- 二.Python string 转 bytes
- 三. Python bytes 转 string
- 四.猜你喜欢
基础 Python 学习路线推荐 : Python 学习目录 >> Python 基础入门
一.Python bytes 和 string 区别
-
1.**Python bytes 也称字节序列,并非字符。取值范围 0 <= bytes <= 255,输出的时候最前面会有字符 b 修饰;string **是 Python 中字符串类型;
-
2.bytes 主要是给在计算机看的,string 主要是给人看的;
-
3.string 经过编码 encode ,转化成二进制对象,给计算机识别;bytes 经过解码 decode ,转化成 string ,让我们看,但是注意反编码的编码规则是有范围, \xc8 就不是 utf8 识别的范围;
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿说编程
@Blog(个人博客地址): www.codersrc.com
@File:Python bytes 和 string 相互转换.py
@Time:2021/04/29 08:00
@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!"""if __name__ == "__main__":# 字节对象bb = b"www.codersrc.com"# 字符串对象ss = "www.codersrc.com"print(b)print(type(b))print(s)print(type(s))'''
输出结果:b'www.codersrc.com'
<class 'bytes'>
www.codersrc.com
<class 'str'>
'''
二.Python string 转 bytes
string 经过编码 encode 转化成 bytes,示例代码如下:
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿说编程
@Blog(个人博客地址): www.codersrc.com
@File:Python bytes 和 string 相互转换.py
@Time:2021/04/29 08:00
@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!"""if __name__ == "__main__":s = "www.codersrc.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'www.codersrc.com'
<class 'bytes'>
b'www.codersrc.com'
<class 'bytes'>'''
三. Python bytes 转 string
bytes 经过解码 decode 转化成 string ,示例代码如下:
if __name__ == "__main__":# 字节对象bb = b"www.codersrc.com"print(b)b = bytes("猿说python", encoding='utf8')print(b)s2 = bytes.decode(b)s3 = b.decode()print(s2)print(s3)'''
输出结果:b'www.codersrc.com'
b'\xe7\x8c\xbf\xe8\xaf\xb4python'
猿说python
猿说python
'''
四.猜你喜欢
- Python for 循环
- Python 字符串
- Python 列表 list
- Python 元组 tuple
- Python 字典 dict
- Python 条件推导式
- Python 列表推导式
- Python 字典推导式
- Python 函数声明和调用
- Python 不定长参数 *argc/**kargcs
- Python 匿名函数 lambda
- Python return 逻辑判断表达式
- Python 字符串/列表/元组/字典之间的相互转换
- Python 局部变量和全局变量
- Python type 函数和 isinstance 函数区别
- Python is 和 == 区别
- Python 可变数据类型和不可变数据类型
- Python 浅拷贝和深拷贝
未经允许不得转载:猿说编程 » Python bytes 和 string 相互转换