Python字符串与bytes的转换

目录

  • 什么是bytes (比特类型)
  • 字符串转bytes的函数–encode
  • bytes转字符串的函数–decode

什么是比特类型

  • 二进制的数据流—bytes
  • 一种特殊的字符串
  • 字符串前+b标记
In [4]: bt = b ' my name is insane'
In [5]: type( bt)
out[5]: bytes

dir(param) 会返回某个数据类型支持的所有函数,比如dir(1)会返回数字类型的所有函数

# coding:utf-8

a = 'hello insane'
print(a, type(a))

b= b'hello insane'
print(b, type(b))

print(b.capitalize())
# print(b.replace('insane', 'loafer'))  # 会报错
print(b.replace(b'insane', b'loafer'))
print(b[0])  # 会将字符转换为二进制类型
print(b[:3])
print(b.find(b'i'))

print(dir(b))  # dir 打印出某个数据类型支持的所有函数

# c = b'hello 小明'  # 会报错,byte只支持ASCII
# print(c)
hello insane <class 'str'>
b'hello insane' <class 'bytes'>
b'Hello insane'
b'hello loafer'
104
b'hel'
6
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'hex', 'index', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Process finished with exit code 0

字符串转bytes的函数-encode功能

  • 将字符串转成比特( bytes)类型

字符串转bytes的函数—encode用法

  • 用法∶string.encode(encoding='utf-8',errors= 'strict')
  • 参数:
    • encoding: 转换成的编码格式,如ascii , gbk,默认utf-8
    • errors: 出错时的处理方法,默认strict,直接抛错误,也可以选择ignore忽略错误
  • 返回值: 返回一个比特( bytes )类型
In [11]: str_data = 'my name is insane'
In [12]: byte_data = str_data.encode( 'utf-8' )
In [13]: byte_data
out[13]: b'my name is insane'

bytes转字符串的函数–decode功能

  • 将比特( bytes)类型转成字符串

bytes转字符串的函数–decode用法

  • 用法: `bytes.decode(encoding=‘utf-8’, errors=‘strict’)
  • 参数:
    • ·encoding·: 转换成的编码格式,如ascii , gbk,默认utf-8
    • ·errors·:出错时的处理方法,默认strict,直接抛错误,也可以选择·ignore·忽略错误
  • 返回值: 返回一个字符串类型
In [15]: byte_data = b'python is a good code'
In [16]: str_data = byte_data.decode( 'utf-8' )
In [17]: str_data
Out[17]: 'python is a good code'

实战

c = 'hello 小明'
d = c.encode('utf-8')
print(d, type(d))
print(d.decode('utf-8'))
b'hello \xe5\xb0\x8f\xe6\x98\x8e' <class 'bytes'>
hello 小明

Process finished with exit code 0
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值