目录
什么是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)
会返回数字类型的所有函数
a = 'hello insane'
print ( a, type ( a) )
b= b'hello insane'
print ( b, type ( b) )
print ( b. capitalize( ) )
print ( b. replace( b'insane' , b'loafer' ) )
print ( b[ 0 ] )
print ( b[ : 3 ] )
print ( b. find( b'i' ) )
print ( dir ( b) )
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的函数—encode用法
用法∶string.encode(encoding='utf-8',errors= 'strict')
参数:
encoding
: 转换成的编码格式,如ascii , gbk,默认utf-8errors
: 出错时的处理方法,默认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转字符串的函数–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