# Python 字符串 Base64

**URL:** <https://www.isharkfly.com/t/python-base64/15646>\
**Category:** 程序语言\
**Tags:** python\
**Created:** [April 16, 2024, 5:28pm UTC](https://www.isharkfly.com/t/python-base64/15646 "2024-04-16T17:28:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hex](https://www.isharkfly.com/user_avatar/www.isharkfly.com/hex/32/21953_2.png) [@hex](https://www.isharkfly.com/u/hex)\
**Post date:** [April 16, 2024, 5:28pm UTC](https://www.isharkfly.com/t/python-base64/15646/1 "2024-04-16T17:28:36Z")

</div>

因消息传输的需要，我们需要对大量文本的字符串进行一下 Base64 转换。

这样的好处是因为在传输的字符串中可能有存在一些特殊字符，这些特殊在经过网络传输的时候会出现编码的问题，并且会影响传输稳定性。

使用 Base64 可以避免这个问题。

 ![2024-04-16_13-23-48](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/3/3de1aee3e1ce6fb36fe5adfc071c3e3446d13e8c.png)

## 方法

Python 的 Base64 后就可以完全只以为 ASCII 码进行传输了。

使用的方法为：

```auto
 base64.b64encode(json.loads(request_detail_data['Data'])['PolicyText'])

```

如果我们直接在上面使用字符串的话，程序会抛出类型错误：

```auto
TypeError: a bytes-like object is required, not 'str'

```

 ![2024-04-16_13-24-00](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/2X/7/72cecadc6c754c6dd0470bfb92c4dda3d1e496e8.png)

方法需要使用的字节码，换句话说就是需要字节对象进行加密，不能直接使用字符串。

可以使用的办法就是把字符串 转换为字节码。

```auto
name.encode('utf-8')

```

### 代码

```auto
bs64name = base64.b64encode(name.encode('utf-8'))

```

哪怕是使用了上面的代码， bs64name为 **bytes** 类型，这就意味着得到的编码结果前带有 b，即b’xxxxxx’。

所以 Python 的 Base64 编码是从字节到字节的。

在完成上面的操作后，我们如果想直接返回字符串，那么我们还需要把字节码转换为字符串。

代码为：

```auto
bbs = str(base64.b64decode(bs64name), "utf-8")

```

上面的输出就为字符串了。

完整的代码为：

```auto
 policy_content = json.loads(request_detail_data['Data'])['PolicyText']
 data['policy_content'] = str(base64.b64encode(policy_content.encode("utf-8")), "utf-8")

```

经过上面 2 次转换就可以完成字符串的编码了。

---

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [April 17, 2024, 4:58pm UTC](https://www.isharkfly.com/t/python-base64/15646/2 "2024-04-17T16:58:47Z")

</div>

对字符串的编码也好还是对 Byte 数组的编码也好，都是针对 2 进制数据的编码。

所以很多编码方式都需要首先把字符串转换 Byte 数组才可以。
