> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/python/python-xiao-ji-qiao/zi-fu-chuan-yu-zi-jie-zhi-jian-zhuan-huan.md).

# 字符串与字节之间转换

## Python中字符串与字节之间相互转换

```
a = b"Hello, world!"   # bytes object
b = "Hello, world!"    # str object
```

#### 字符串转字节 str --> bytes

```
# 字符串转字节  str --> bytes
print(str.encode(b))  # 默认 encoding="utf-8"
print(bytes(b, encoding="utf8"))
print(b.encode())      # 默认 encoding="utf-8"
```

#### 字节转字符串 bytes --> str

```
# 字节转字符串  bytes --> str
print(bytes.decode(a))   # 默认encoding="utf-8"
print(str(a, encoding="utf-8"))
print(a.decode())       # 默认 encoding="utf-8"
```
