python常用工具小函数-字符类型转换

时间:2023-03-09 18:26:12
python常用工具小函数-字符类型转换

  Python3有两种表示字符序列的类型:bytes和str。前者的实例包含原始的8位值就是的字节,每个字节有8个二进制位;后者的实例包含Unicode字符。把Unicode字符转成二进制数据最常见的编码方式就是UTF-8,必须使用encode方法;把二进制数据转成Unicode字符必须使用decode方法。

  实际开发中我们经常需要在这两种字符类型间转换,所以需要写两个辅助函数,以便在这两种情况之间转换,使得转换后的输入数据能够符合我们的预期。

1、接受str或bytes,并总是返回str的方法:

def to_str(str_or_bytes):

  if isinstance(str_or_bytes,bytes):

    value = str_or_bytes.decode('utf-8')

  else:

    value = str_or_bytes

  return value

2、接受str或bytes,并总是返回bytes的方法:

def to_bytes(str_or_bytes):

  if isinstance(str_or_bytes,str):

    value = str_or_bytes.encode('utf-8')

  else:

    value = str_or_bytes

  return value