基本的byte数据类型创建:
name = bytes('aike',encoding='utf-8')#通过bytes关键字创建 name1 = b'aike'#直接指定字符串为bytes类型 print(name) print(name1)
均输出:
b'aike' #以b开头
字符串类型转换成byte类型用encode:
name = '艾克' age = '18' n = name.encode('utf-8') a = age.encode('utf-8') print(n) print(a)
输出:
b'xe8x89xbexe5x85x8b' #中文以十六进制形式输出 b'18'
将byte数据类型进行解码用decode:
name = '艾克' age = '18' n = name.encode('utf-8') a = age.encode('utf-8') print(n) print(a) nb = n.decode('utf-8') ab = a.decode('utf-8') print(nb) print(ab)
输出:
b'xe8x89xbexe5x85x8b' b'18' 艾克 18