gpt4 book ai didi

python - 在base64字符串中每76个字符后插入换行符

转载 作者:太空狗 更新时间:2023-10-29 20:36:17 24 4
gpt4 key购买 nike

我正在尝试将位图图像转换为 base64 字符串,然后再将其作为二进制 blob 插入数据库。 base64 字符串需要以每 76 个字符后一个换行符的方式进行编码。执行此操作的最佳 pythonic 方法是什么?

最佳答案

对于 Python 版本 3:

import base64
base64.encodebytes(s)

https://docs.python.org/3/library/base64.html#base64.encodebytes

Encode the bytes-like object s, which can contain arbitrary binary data, and return bytes containing the base64-encoded data, with newlines (b'\n') inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME).

例子:

>>> print(base64.encodebytes(b'a' * 100).decode())
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==

>>>

对于 Python 版本 2:

import base64
base64.encodestring(s)

http://docs.python.org/library/base64.html

Encode the string s, which can contain arbitrary binary data, and return a string containing one or more lines of base64-encoded data. encodestring() returns a string containing one or more lines of base64-encoded data always including an extra trailing newline ('\n').

第 2 版的文档当然可以写得更清楚,但它可以满足您的要求。

例子:

>>> print base64.encodestring('a'*100)
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==

>>>

关于python - 在base64字符串中每76个字符后插入换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2871933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com