将 ascii 字符串转换为 base64,不带“b";和引号

Convert ascii string to base64 without the quot;bquot; and quotation marks(将 ascii 字符串转换为 base64,不带“b;和引号)
本文介绍了将 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";和引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)