Python bytes 和 string 相互转换 - Python零基础入门教程

目录

基础 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 浅拷贝和深拷贝

未经允许不得转载:猿说编程 » Python bytes 和 string 相互转换

本文由博客 - 猿说编程 猿说编程 发布!

posted @ 2021-06-21 14:24  猿说编程  阅读(1223)  评论(0编辑  收藏  举报