将不带"b"的ascii字符串转换为base64.和引号 [英] Convert ascii string to base64 without the "b" and quotation marks

查看:121
本文介绍了将不带"b"的ascii字符串转换为base64.和引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个ascii字符串(准确地说就是文本)转换为base64. 所以我知道该怎么做,我只使用以下代码:

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)

哪个给我

b'c3RyaW5n'

但是问题是,我希望它仅打印

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

c3RyaW5n

是否可以打印不带"b"和"引号的字符串? 谢谢!

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

推荐答案

b前缀表示它是二进制字符串.二进制字符串不是 字符串:它是字节序列(值在0到255之间).只是将它排版为字符串以使其更紧凑.

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.

但是,在base64的情况下,所有字符都是有效的ASCII字符,因此您可以像下面这样简单地对其进行解码:

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

print(string.decode('ascii'))

因此,在这里,我们将每个字节解码为等效的ASCII码.由于base64保证它产生的每个字节都在ASCII范围('A''/')中,因此我们将始终产生一个有效的字符串.但是请注意,使用任意二进制字符串不能保证 .

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.

这篇关于将不带"b"的ascii字符串转换为base64.和引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆