如何在python中将文本编码为base64
我想把一段文本字符串转换成base64格式。
我试着这样做:
name = "your name"
print('encoding %s in base64 yields = %s\n'%(name,name.encode('base64','strict')))
但是我遇到了以下错误:
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs
我该怎么做呢?(使用Python 3.4)
9 个回答
5
看起来,即使在对经过 base64
编码的字符串使用了 base64.b64decode
之后,调用 decode()
函数也是很重要的,这样才能真正使用字符串数据。因为要记住,它总是返回字节类型的数据。
import base64
conv_bytes = bytes('your string', 'utf-8')
print(conv_bytes) # b'your string'
encoded_str = base64.b64encode(conv_bytes)
print(encoded_str) # b'eW91ciBzdHJpbmc='
print(base64.b64decode(encoded_str)) # b'your string'
print(base64.b64decode(encoded_str).decode()) # your string
17
1) 在Python 2中,这个代码可以直接使用,不需要导入任何东西:
>>>
>>> 'Some text'.encode('base64')
'U29tZSB0ZXh0\n'
>>>
>>> 'U29tZSB0ZXh0\n'.decode('base64')
'Some text'
>>>
>>> 'U29tZSB0ZXh0'.decode('base64')
'Some text'
>>>
(不过在Python 3中就不行了)
2) 在Python 3中,你需要先导入base64这个模块,然后用base64.b64decode('...')来解码 - 这个方法在Python 2中也可以用。
31
结果发现,这个问题的重要性足够高,居然有了专门的模块来处理它……
import base64
base64.b64encode(b'your name') # b'eW91ciBuYW1l'
base64.b64encode('your name'.encode('ascii')) # b'eW91ciBuYW1l'
36
对于 py3
,这里是如何对字符串进行 base64 编码和解码:
import base64
def b64e(s):
return base64.b64encode(s.encode()).decode()
def b64d(s):
return base64.b64decode(s).decode()
162
记得要导入 base64
模块,并且 b64encode
函数需要传入字节类型的数据。
import base64
b = base64.b64encode(bytes('your_string', 'utf-8')) # bytes
base64_str = b.decode('utf-8') # convert bytes to string
解释:
bytes
函数可以把字符串 "your_string" 转换成字节对象,这个过程是通过 UTF-8 编码来实现的。在 Python 中,bytes
代表一串二进制数据,而 UTF-8 则是用来定义字符编码的方式。
base64.b64encode
函数的作用是把字节对象转换成 Base64 格式。它需要一个字节类型的数据作为输入,然后返回一个经过 Base64 编码的字节对象。
b.decode
函数则是用 UTF-8 编码来解码字节对象(这里是 b
),并返回解码后的字符串。也就是说,它把字节数据转换回原来的字符串形式。