effective python-bytes和str的区别

effective python-bytes和str的区别,第1张

bytes和str的区别
  • bytes:实例包含的是原始数据,即 8 位的无符号值(通常按照 ASCII 编码标准来显示)

  • str:实例包含的是 Unicode 码点(code point,也叫作代码点),这些码点与人类语言之中的文本字符相对应

通过两个辅助函数来转换bytes和str类型的字符

Unicode数据 和 二级制数据的转换
bytes -> str decode解码
str -> bytes encode编码

bytes -> str decode解码

from typing import Union


def to_str(bytes_or_str: Union[str, bytes]):
    """
    :param bytes_or_str: str/bytes
    :return: str类型
    """
    if isinstance(bytes_or_str, bytes):
        value = bytes_or_str.decode("utf-8")
    else:
        value = bytes_or_str
    return value

str -> bytes encode编码

from typing import Union


def to_bytes(bytes_or_str: Union[str, bytes]):
    """
    :param bytes_or_str: str/bytes
    :return: bytes类型
    """
    if isinstance(bytes_or_str, str):
        value = bytes_or_str.encode("utf-8")
    else:
        value = bytes_or_str
    return value

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/942762.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-18
下一篇2022-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存