Python3 - 如何将string转换成数组

Python3 - 如何将string转换成数组

可通过encode 和 decode进行string和bytes转换

1
2
str = str.encode('UTF-8','strict');
str.decode(encoding='UTF-8,errors='strict')

下面代码片段展示如何将string转换成bytes

  1. string 转换成 bytes.
1
2
3
data = 'we are what we think we are'  			#string
bys = data.encode('UTF-8')	#bytes
print(bys)

输出:

1
>>> b'we are what we think we are'
  1. bytes 转换成 string
1
2
3
4
data = b'we are what we think we are'  		#bytes
str = data.decode('UTF-8') #string
print(str)

控制台输出:

1
>>>> we are what we think we are

上述代码在python3.7.6测试通过

Rating: