python将UTF-8编码的字符串转换为字节数组
时间: 2023-05-15 09:06:21 浏览: 76
可以使用encode()方法将UTF-8编码的字符串转换为字节数组,例如:
```
s = "你好,世界!"
b = s.encode('utf-8')
print(b)
```
输出结果为:
```
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
```
相关问题
python utf-8编码的字符转成字节数组
你可以使用 Python 的 `encode()` 函数将 UTF-8 编码的字符串转换为字节数组。例如:
```python
s = "你好,世界!"
b = s.encode("utf-8")
print(list(b))
```
输出结果为:
```
[228, 189, 160, 229, 165, 189, 239, 188, 129, 231, 171, 153, 239, 188, 140, 33]
```
在这个例子中,`encode()` 函数将字符串 `s` 转换为一个字节数组 `b`,其中每个 Unicode 字符被编码为一个或多个字节。最后,使用 `list()` 函数将字节数组转换为一个整数列表,以方便查看每个字节的值。
Python将字节数组8转换为字符串
可以使用Python的`decode()`方法将字节数组转换为字符串。具体代码如下:
```python
byte_array = b'\x68\x65\x6c\x6c\x6f'
string = byte_array.decode('utf-8')
print(string)
```
输出结果为:`hello`。其中,`b'\x68\x65\x6c\x6c\x6f'`表示字节数组,使用`decode()`方法将其转换为字符串,参数`'utf-8'`表示字节数组的编码方式为UTF-8。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)