【问题标题】:Multi line base64 string returns only last line after decoding in Python 3在 Python 3 中解码后,多行 base64 字符串仅返回最后一行
【发布时间】:2020-08-17 12:14:08
【问题描述】:

我有一组 base64 编码的字符串。当我尝试解码时,解码后的文本只有实际字符串的最后一行。在任何在线 base64 解码器上,都会显示整个文本。在解码之前,我尝试过将文本编码为 utf-8 和不编码。 这是我的代码:

import base64

encodedStr = "QXJyaXZhbCBNZXNzYWdlDURhdGUgKFVUQyk6IDI2SlVMMjAN"

#with encoding
encodedstr_bytes = encodedStr.encode('utf-8')
decodedBytes = base64.b64decode(encodedstr_bytes)
decodedStr = decodedBytes.decode('utf8')
print(decodedStr)  


#without encoding
decodedBytes = base64.b64decode(encodedStr)
decodedStr = decodedBytes.decode("utf-8")
print(decodedStr)

Output : 

Date (UTC): 26JUL20
Date (UTC): 26JUL20



Required Output : 

Arrival Message
Date (UTC): 26JUL20

【问题讨论】:

  • 欢迎来到本站。代码示例没有按照我的描述运行。解码后的字符串是否包含您不想要的其他数据?例如它看起来像'Arrival Message\rDate (UTC): 26JUL20\r' 而你只想要26JUL20?两个版本对我来说都给出了相同的结果。完整的字符串,包括“到达消息”。
  • 当我执行代码时,我只得到第二行 'Date (UTC): 26JUL20' 而不是全文。我也想提取第一行('Arrival Message')

标签: python base64


【解决方案1】:

您的字符串有回车符(“\r”),但没有换行符(“\n”)。在 Windows 上,这会指示打印机返回到行首并覆盖那里的内容。以下代码的行为相同:

print("foo\rbar")  # Prints "bar"
print("fooqux\rbar")  # Prints "barqux"

【讨论】:

  • 感谢您的解释!!!由于这个原因,它在 linux 和任何在线编辑器上都可以正常工作。 print(decodedStr.replace('\r','\r\n')) -- 这在 Windows 中有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 2014-11-17
  • 2011-10-18
相关资源
最近更新 更多