# bytes
orig_bytes = b"my is a bytes"
# str
orig_str = "my is a sting"
第一种方法:
# str转换为bytes
bytes(orig_str, encoding = 'utf-8')
bytes(orig_str, 'utf-8')
# bytes转换为str
str(orig_bytes, encoding = 'utf-8')
str(orig_bytes, 'utf-8')
第二种方法:
# str转换为bytes
str.encode(orig_str)
# bytes转换为str
bytes.decode(orig_bytes)
In [2]: # bytes
...: orig_bytes = b"my is a bytes"
...: # str
...: orig_str = "my is a sting"
In [3]: '''第一种方法'''
...: # str转换为bytes
...: bytes(orig_str, encoding = 'utf-8')
Out[3]: b'my is a sting'
In [4]: # bytes转换为str
...: str(orig_bytes, encoding = 'utf-8')
Out[4]: 'my is a bytes'
In [5]: '''第二种方法'''
...: # str转换为bytes
...: str.encode(orig_str)
Out[5]: b'my is a sting'
In [6]: # bytes转换为str
...: bytes.decode(orig_bytes)
Out[6]: 'my is a bytes'