赞
踩
+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
string.encode(encoding='utf-8',errors= 'strict')
encoding
: 转换成的编码格式,如ascii , gbk,默认utf-8errors
: 出错时的处理方法,默认strict,直接抛错误,也可以选择ignore
忽略错误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'
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。