如何在 python 3 中使用 base64 对字符串进行编码并删除新行
How to encode a string with base64 in python 3 and remove the new lines
背景:
我正在尝试将我的用户名和密码字符串编码为 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") )
base64 的替代方法:
import codecs
codecs.encode(bytes("mystring", 'utf8'), 'base64')
背景:
我正在尝试将我的用户名和密码字符串编码为 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") )
base64 的替代方法:
import codecs
codecs.encode(bytes("mystring", 'utf8'), 'base64')