利用python设计:要求输入字符串可以输出Base64编码,输入Base64编码值可以转为字符串
时间: 2024-01-22 19:17:26 浏览: 25
可以使用Python中的base64模块来实现字符串和Base64编码之间的转换。下面是一个示例代码:
```python
import base64
def str_to_base64(s):
b = s.encode('utf-8')
b64 = base64.b64encode(b)
return b64.decode('utf-8')
def base64_to_str(b64):
b = b64.encode('utf-8')
s = base64.b64decode(b)
return s.decode('utf-8')
```
上述代码中,`str_to_base64`函数接收一个字符串作为输入,并返回其Base64编码。`base64_to_str`函数接收一个Base64编码作为输入,并返回其解码后的字符串。
例如:
```python
s = 'Hello, world!'
b64 = str_to_base64(s)
print(b64) # 'SGVsbG8sIHdvcmxkIQ=='
s2 = base64_to_str(b64)
print(s2) # 'Hello, world!'
```
注意,在将字符串编码为Base64时,需要先将其转换为字节串,然后再进行编码。同样,在将Base64解码为字符串时,需要先将其解码为字节串,然后再进行解码。
相关问题
python 将 base64 编码的字符串转换为图片
可以使用 Python 的 base64 模块来解码 base64 编码的字符串,然后将其写入文件中,从而生成图片。以下是一个示例代码:
```python
import base64
# 读取 base64 编码的字符串
with open('image.txt', 'r') as f:
image_data = f.read()
# 解码 base64 字符串
image_binary = base64.b64decode(image_data)
# 将二进制数据写入图片文件
with open('image.jpg', 'wb') as f:
f.write(image_binary)
```
在上面的代码中,我们首先从文件中读取 base64 编码的字符串,然后使用 `base64.b64decode()` 方法将其解码为二进制数据。最后,我们将二进制数据写入一个新的图片文件中。注意,图片格式需要与原来的图片格式一致。
如何把字符串转base64编码
您可以使用Python中的base64模块来将字符串转换为base64编码。以下是示例代码:
```python
import base64
string = "Hello, World!" # 待编码的字符串
string_bytes = string.encode('utf-8') # 将字符串转换为字节
encoded_string_bytes = base64.b64encode(string_bytes) # 将字节编码为base64
encoded_string = encoded_string_bytes.decode('utf-8') # 将字节转换为字符串
print(encoded_string) # 输出编码后的字符串
```
输出结果为:
```
SGVsbG8sIFdvcmxkIQ==
```
其中,`SGVsbG8sIFdvcmxkIQ==`就是`Hello, World!`的base64编码。