Convert ascii string to base64 without the “b” and quotation marks

筅森魡賤 提交于 2020-02-03 08:26:43

问题


I wanted to convert an ascii string (well just text to be precise) towards base64. So I know how to do that, I just use the following code:

import base64
string = base64.b64encode(bytes("string", 'utf-8'))
print (string)

Which gives me

b'c3RyaW5n'

However the problem is, I'd like it to just print

c3RyaW5n

Is it possible to print the string without the "b" and the '' quotation marks? Thanks!


回答1:


The b prefix denotes that it is a binary string. A binary string is not a string: it is a sequence of bytes (values in the 0 to 255 range). It is simply typesetted as a string to make it more compact.

In case of base64 however, all characters are valid ASCII characters, you can thus simply decode it like:

print(string.decode('ascii'))

So here we will decode each byte to its ASCII equivalent. Since base64 guarantees that every byte it produces is in the ASCII range 'A' to '/') we will always produce a valid string. Mind however that this is not guaranteed with an arbitrary binary string.




回答2:


A simple .decode("utf-8") would do

import base64
string = base64.b64encode(bytes("string", 'utf-8'))
print (string.decode("utf-8"))


来源:https://stackoverflow.com/questions/45151023/convert-ascii-string-to-base64-without-the-b-and-quotation-marks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!