当我完成解码和编码时,为什么字符串末尾会有换行符?

qua*_*els 6 python base64 encoding python-2.7

这是我的代码:

def hex_to_base64(hex_string):
    clear = hex_string.decode("hex")
    print(clear)
    base64 = clear.encode("base64")
    print(base64)
    return base64

hexstring = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
result = hex_to_base64(hexstring)

# verify results
if result == 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t':
    print("Yuuuup!!! %r" % result)
else:
    print("Nope! %r" % result)
Run Code Online (Sandbox Code Playgroud)

我的结果验证测试失败了.打印出来:

Nope! 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\n'
Run Code Online (Sandbox Code Playgroud)

'\n'换行符来自何处?我可以脱掉它以让测试通过,但我觉得这是作弊.

Mar*_*ers 9

Base64编码包括:

>>> 'a'.encode('base64')
'YQ==\n'
Run Code Online (Sandbox Code Playgroud)

其他Base64编码方法也包括换行符; 看看base64.encode()例如:

encode()返回编码数据和尾随换行符('\n').

选择似乎是历史性的; MIME Base64 content-transfer-encoding规定使用最大行长度并插入换行符以保持该长度,但RFC 3548规定实现不得.

Python提供了两种选择; 你可以在这里使用这个base64.b64encode()功能:

>>> import base64
>>> base64.b64encode('a')
'YQ=='
Run Code Online (Sandbox Code Playgroud)