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

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

问题描述

我想将一个 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 保证它产生的每个字节都在 'A''/' 的 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.

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

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