Skip to content

Commit 4a4351a

Browse files
committed
6.10小节完成
1 parent ec8a58e commit 4a4351a

3 files changed

Lines changed: 60 additions & 4 deletions

File tree

‎cookbook/c06/p10_codec_base64.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
"""
4+
Topic: 编码/解码Base64
5+
Desc :
6+
"""
7+
import base64
8+
9+
10+
def codec_base64():
11+
s = b'hello'
12+
13+
# Encode as Base64
14+
a = base64.b64encode(s)
15+
print(a)
16+
17+
# Decode from Base64
18+
b = base64.b64decode(a)
19+
print(b)
20+
21+
if __name__ == '__main__':
22+
codec_base64()
23+
24+

‎source/c06/p09_decode_encode_hexadecimal_digits.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,4 @@
6363
>>>
6464
6565
在解码十六进制数时,函数 ``b16decode()`` 和 ``a2b_hex()`` 可以接受字节或unicode字符串。
66-
然而,这些字符串必须仅仅只包含ASCII编码的十六进制数。
66+
但是,unicode字符串必须仅仅只包含ASCII编码的十六进制数。

‎source/c06/p10_decode_encode_base64.rst‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,46 @@
55
----------
66
问题
77
----------
8-
todo...
8+
你需要使用Base64格式解码或编码二进制数据。
9+
10+
|
911
1012
----------
1113
解决方案
1214
----------
13-
todo...
15+
``base64`` 模块中有两个函数 ``b64encode()`` and ``b64decode()`` 可以帮你解决这个问题。例如;
16+
17+
.. code-block:: python
18+
19+
>>> # Some byte data
20+
>>> s = b'hello'
21+
>>> import base64
22+
23+
>>> # Encode as Base64
24+
>>> a = base64.b64encode(s)
25+
>>> a
26+
b'aGVsbG8='
27+
28+
>>> # Decode from Base64
29+
>>> base64.b64decode(a)
30+
b'hello'
31+
>>>
32+
33+
|
1434
1535
----------
1636
讨论
1737
----------
18-
todo...
38+
Base64编码仅仅用于面向字节的数据比如字节字符串和字节数组。
39+
此外,编码处理的输出结果总是一个字节字符串。
40+
如果你想混合使用Base64编码的数据和Unicode文本,你必须添加一个额外的解码步骤。例如:
41+
42+
.. code-block:: python
43+
44+
>>> a = base64.b64encode(s).decode('ascii')
45+
>>> a
46+
'aGVsbG8='
47+
>>>
48+
49+
当解码Base64的时候,字节字符串和Unicode文本都可以作为参数。
50+
但是,Unicode字符串只能包含ASCII字符。

0 commit comments

Comments
 (0)