python bytes转str 的所有方法
时间: 2024-05-09 22:19:14 浏览: 117
1. 使用bytes的decode()方法:
```python
bytes_obj = b'hello'
str_obj = bytes_obj.decode('utf-8')
```
2. 使用str的encode()方法:
```python
bytes_obj = str_obj.encode('utf-8')
```
3. 使用str的join()方法:
```python
bytes_obj = b''.join([bytes([i]) for i in str_obj])
```
4. 使用str的replace()方法和bytes的join()方法:
```python
bytes_obj = b''.join(str_obj.replace(chr(i), bytes([i])) for i in range(256))
```
5. 使用struct模块的unpack()方法:
```python
import struct
bytes_obj = b'hello'
str_obj = struct.unpack('5s', bytes_obj)[0].decode('utf-8')
```
6. 使用binascii模块的b2a_hex()方法和a2b_hex()方法:
```python
import binascii
bytes_obj = b'hello'
hex_str = binascii.b2a_hex(bytes_obj).decode('utf-8')
str_obj = binascii.a2b_hex(hex_str).decode('utf-8')
```
阅读全文