【python初级】 将字符串转化为字节
- 1、背景
- 2、内置函数bytes
- 3、字符串的encode方法
1、背景
在对账户、密码等私密数据加密过程中会用到字节码。
python3将字符串转化成字节码有两种方法:
-1.1 内置函数bytes;
-1.2 字符串的encode方法;
2、内置函数bytes
内置函数bytes函数返回一个新的 bytes 类型。
示例如下:
# coding:utf-8
# jn10010537
str1="jn10010537"
bytes_obj = bytes(str1,'utf-8')
print("bytes_obj:",bytes_obj)
print("type(bytes_obj):",type(bytes_obj))
'''
运行如下:
bytes_obj: b'jn10010537'
type(bytes_obj): <class 'bytes'>
'''
3、字符串的encode方法
使用字符串的encode方法,将字符串编码成字节。
如果未指定编码,则将使用UTF-8。
示例如下:
# coding:utf-8
# jn10010537
str1="jn10010537"
bytes_obj = str1.encode('utf-8')
print("bytes_obj:",bytes_obj)
print("type(bytes_obj):",type(bytes_obj))
'''
运行如下:
bytes_obj: b'jn10010537'
type(bytes_obj): <class 'bytes'>
'''