Python bytes 和 string 相互转换

ChatGPT 3.5 国内中文镜像站免费使用啦

基础 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__":
    # 字节对象b
    b = b"www.codersrc.com"
    # 字符串对象s
    s = "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__":
    # 字节对象b
    b = 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
'''

四.猜你喜欢

  1. Python for循环
  2. Python 字符串
  3. Python 列表list
  4. Python 元组tuple
  5. Python 字典 dict
  6. Python 条件推导式
  7. Python 列表推导式
  8. Python 字典推导式
  9. Python 函数声明和调用
  10. Python 不定长参数 *argc/**kargcs
  11. Python 匿名函数 lambda
  12. Python return 逻辑判断表达式
  13. Python 字符串/列表/元组/字典之间的相互转换
  14. Python 局部变量和全局变量
  15. Python type 函数和 isinstance 函数区别
  16. Python is 和 == 区别
  17. Python 可变数据类型和不可变数据类型
  18. Python 浅拷贝和深拷贝

ChatGPT 3.5 国内中文镜像站免费使用啦
文章版权声明 1、本网站名称:猿说编程
2、本站永久网址:https://www.codersrc.com
3、本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
4、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
5、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
6、本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。

© 版权声明
THE END
喜欢就支持一下吧
点赞2 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容