gpt4 book ai didi

python - 如何在python 3中使用base64对字符串进行编码并删除新行

转载 作者:行者123 更新时间:2023-11-30 22:47:41 25 4
gpt4 key购买 nike

背景:

我正在尝试将用户名和密码字符串编码为 Base 64,以便在 python 3.5.2 中发出 SOAP 请求。

代码:

username = 'Universal API/uAPI7054626850-8a6c09f0'
password = 'gaghw3d5WCw3QCzTMh3QJ5fDp'
base64string = '%s:%s' % (username, password)
resultValue = base64string.encode('base64', 'strict')

此代码已从以下示例中准确复制:https://www.tutorialspoint.com/python/string_encode.htm

错误:

Traceback (most recent call last):
File "soapRequests.py", line 44, in <module>
resultValue = base64string.encode('base64', 'strict')
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

尝试:

Attempt 1: using the base64 codec
base64string = base64.encodestring(base64string).replace('\n', '')
Result: TypeError: expected bytes-like object, not str

如果您知道如何将字符串编码为 Base64 编解码器,请告诉我。谢谢

答案:

我几乎不知道错误来自于对字符串进行编码后使用的替换函数。使用 b64encode,这样您就不必编写自己的替换函数来替换新行。

最佳答案

试试这个:

base64string = base64.b64encode( bytes(base64string, "utf-8") )

关于python - 如何在python 3中使用base64对字符串进行编码并删除新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40454177/

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