【问题标题】:How to encode a string with base64 in python 3 and remove the new lines [duplicate]如何在python 3中使用base64编码字符串并删除新行[重复]
【发布时间】:2016-11-06 20:29:26
【问题描述】:

背景:

我正在尝试将我的用户名和密码字符串编码为 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 这样您就不必编写自己的替换函数来替换新行。

【问题讨论】:

    标签: python base64 encode python-3.5


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 非常感谢!我的问题是因为替换函数试图替换字节值上的字符串。这是答案,因为 b64encode 删除了 '\n'
    【解决方案2】:

    base64 的替代方案:

    import codecs
    
    codecs.encode(bytes("mystring", 'utf8'), 'base64')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-08
      • 2011-12-03
      • 2013-06-04
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2019-09-27
      相关资源
      最近更新 更多