首页 > 代码库 > python常用工具小函数-字符类型转换
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 = http://www.mamicode.com/str_or_bytes.decode(‘utf-8‘)
else:
value = http://www.mamicode.com/str_or_bytes
return value
2、接受str或bytes,并总是返回bytes的方法:
def to_bytes(str_or_bytes):
if isinstance(str_or_bytes,str):
value = http://www.mamicode.com/str_or_bytes.encode(‘utf-8‘)
else:
value = http://www.mamicode.com/str_or_bytes
return value
python常用工具小函数-字符类型转换
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。