python中bytes类型转成str
时间: 2023-04-27 12:06:20 浏览: 82
在Python中,可以使用decode()方法将bytes类型转换为str类型。例如:
```
b = b'hello'
s = b.decode('utf-8')
print(s)
```
输出结果为:
```
hello
```
相关问题
python中class bytes转str
在 Python 中,可以使用 `decode()` 方法将 `bytes` 类型转换为 `str` 类型。示例如下:
```python
b = b'hello'
s = b.decode('utf-8')
print(s) # 输出:hello
```
其中,`decode()` 方法可以指定解码格式,默认为 `'utf-8'`。如果 `bytes` 中的内容不符合解码格式,则会抛出异常。如果你不确定解码格式,可以尝试多种格式进行解码,直到不抛异常为止。例如:
```python
b = b'\xe4\xbd\xa0\xe5\xa5\xbd'
try:
s = b.decode('utf-8')
except UnicodeDecodeError:
s = b.decode('gbk')
print(s) # 输出:你好
```
python bytes16进制转str
可以使用 Python 的内置函数 `bytes.fromhex()` 将 16 进制字符串转换为 bytes 对象,然后再使用 `.decode()` 方法将其转换为字符串。示例代码如下:
```python
hex_str = "68656c6c6f20776f726c64"
byte_obj = bytes.fromhex(hex_str)
str_obj = byte_obj.decode('utf-8')
print(str_obj) # 输出:hello world
```
上述代码中,我们将 16 进制字符串 `"68656c6c6f20776f726c64"` 转换为 bytes 对象 `byte_obj`,然后使用 `decode()` 方法将其转换为字符串 `str_obj`。其中,`decode()` 方法的参数指定了解码字符集,这里使用的是 UTF-8 编码。