python2与python3下的base64模块
Python2的编解码
python2中程序数据类型默认为ASCII,所以需要先将数据解码(decode)成为Unicode类型,然后再编码(encode)成为想要转换的数据类型(gbk,utf-8,gb18030,gb2312),然后再解码成为对应的数据类型显示在屏幕上;
Python3的编解码
python3中程序默认数据类型为Unicode,所以直接将数据编码(encode)成为想要转换的数据类型(gbk,utf-8,gb18030,gb2312),然后解码成为对应的数据类型显示在屏幕上。
base64
Base64编码是一种“防君子不防小人”的编码方式。广泛应用于MIME协议,作为电子邮件的传输编码,生成的编码可逆,后一两位可能有“=”,生成的编码都是ascii字符。
因此对于python2来说,编解码相对要容易一些。python3因为要从Unicode转换一下,相对麻烦一些。一切见下例:
- Python2
def b64encode(s, altchars=None):
"""Encode a string using Base64. s is the string to encode. Optional altchars must be a string of at least
length 2 (additional characters are ignored) which specifies an
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings. The encoded string is returned.
"""
# Strip off the trailing newline
encoded = binascii.b2a_base64(s)[:-1]
if altchars is not None:
return encoded.translate(string.maketrans(b'+/', altchars[:2]))
return encoded
def b64decode(s, altchars=None):
"""Decode a Base64 encoded string. s is the string to decode. Optional altchars must be a string of at least
length 2 (additional characters are ignored) which specifies the
alternative alphabet used instead of the '+' and '/' characters. The decoded string is returned. A TypeError is raised if s is
incorrectly padded. Characters that are neither in the normal base-64
alphabet nor the alternative alphabet are discarded prior to the padding
check.
"""
if altchars is not None:
s = s.translate(string.maketrans(altchars[:2], '+/'))
try:
return binascii.a2b_base64(s)
except binascii.Error, msg:
# Transform this exception for consistency
raise TypeError(msg)
b64decode源码
这里面的s是一个字符串类型的对象。
import base64 s = 'Hello, python'
b = base64.b64encode(s)
print 'b为:', b c = base64.b64decode(b)
print 'c为:', c # output
b为: SGVsbG8sIHB5dGhvbg==
c为: Hello, python
- Python3
def b64encode(s, altchars=None):
"""Encode the bytes-like object s using Base64 and return a bytes object. Optional altchars should be a byte string of length 2 which specifies an
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
"""
encoded = binascii.b2a_base64(s, newline=False)
if altchars is not None:
assert len(altchars) == 2, repr(altchars)
return encoded.translate(bytes.maketrans(b'+/', altchars))
return encoded
def b64decode(s, altchars=None, validate=False):
"""Decode the Base64 encoded bytes-like object or ASCII string s. Optional altchars must be a bytes-like object or ASCII string of length 2
which specifies the alternative alphabet used instead of the '+' and '/'
characters. The result is returned as a bytes object. A binascii.Error is raised if
s is incorrectly padded. If validate is False (the default), characters that are neither in the
normal base-64 alphabet nor the alternative alphabet are discarded prior
to the padding check. If validate is True, these non-alphabet characters
in the input result in a binascii.Error.
"""
s = _bytes_from_decode_data(s)
if altchars is not None:
altchars = _bytes_from_decode_data(altchars)
assert len(altchars) == 2, repr(altchars)
s = s.translate(bytes.maketrans(altchars, b'+/'))
if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
raise binascii.Error('Non-base64 digit found')
return binascii.a2b_base64(s)
b64decode源码
这里面的s是一个bytes对象,则字符串首先要经过编码encode()。经过b64encode/b64decode之后的返回结果也是bytes对象,所以我们要转换为Unicode对象就要再使用decode()方法去解码。
import base64 s = 'Hello, Python!'
b = base64.b64encode(s.encode('utf-8')).decode('utf-8')
print(b) c = base64.b64decode(b.encode('utf-8')).decode('utf-8')
print(c) # output
SGVsbG8sIFB5dGhvbiE=
Hello, Python!
python2与python3下的base64模块的更多相关文章
- python在Linux中安装虚拟环境,区别python2和python3,分别安装模块
安装虚拟环境的时候遇到的问题,解决的过程很闹心,在这里简单直接的分享出来,就是为了解决问题. 安装虚拟环境(须在联网状态下) $ sudo pip install virtualenv $ sudo ...
- Python3下的paramiko模块
paramiko模块是基于Python实现的SSH远程安全连接,用于SSH远程执行命令.文件传输等功能. 默认Python没有,需要手动安装:pip install paramiko SSH密码认证远 ...
- python2和python3中的编码问题
开始拾起python,准备使用python3, 造轮子的过程中遇到了编码的问题,又看了一下python3和python2相比变化的部分. 首先说个概念: unicode:在本文中表示用4byte表示的 ...
- win10下python2与python3以及pip共存
一 分别安装python2和python3 注意: 安装时记得勾选 Add Python.exe to Path 二 安装pip Python3最新版本有pip,无需安装 Python2: 下载pip ...
- win10下安装python2与python3以及pip共存
一 分别安装python2和python3 注意: 安装时记得勾选 Add Python.exe to Path 二 安装pip Python3最新版本有pip,无需安装 Python2: 下载pip ...
- python2.7环境下的flask项目导入模块失败解决办法
如下一个flask项目的目录: 这个flask项目在python3.6环境下可以正常启动,但是在python2.7环境下如下报错提示: 提醒模块找不到.如下解决方法: 只需要在views目录里面加一个 ...
- Windows下Python2与Python3两个版本共存的方法详解
来源:http://www.jb51.net/article/105311.htm 这篇文章主要介绍了Windows下Python2与Python3两个版本共存的方法,文中介绍的很详细,对大家具有一定 ...
- python3下的IE自动化模块PAMIE
PAMIE是Python下面的用于IE的自动化模块,支持python2和python3,python3的下载地址:http://sourceforge.net/projects/pamie/files ...
- Windows下安装python2与python3以及分别对应的virtualenv
第三次装python2与python3 除此之外还学会了如何在命令行复制代码1.单击右键2.菜单中选择标记3.按住左键选中需要复制的内容4.松开左键5.单击右键 全局中python版本为python2 ...
随机推荐
- PIL基础操作
PIL基础操作 新建图片 from PIL import Image # 通常使用RGB模式就可以了 new_img = Image.new('RGB', (100, 100), 'red') new ...
- 1105 Spiral Matrix(25 分)
This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasi ...
- C# ThreadLocal
ThreadLocal的主要作用是让各个线程维持自己的变量. .NET 4.0在线程方面加入了很多东西,其中就包括ThreadLocal<T>类型,他的出现更大的简化了TLS的操作.Thr ...
- @Inherited:允许子类继承父类的注解。
在看定义注解的相关文章的时候,看到这个@Inherited注解,简单的说明并没有真正搞懂是什么意思.在网上搜索了一些相关的内容,现在把一篇文章转载过来.以便后面使用. 文章出处,转载地址:(http: ...
- Spring Security方法级别授权使用介绍
1.简介 简而言之,Spring Security支持方法级别的授权语义. 通常,我们可以通过限制哪些角色能够执行特定方法来保护我们的服务层 - 并使用专用的方法级安全测试支持对其进行测试. 在本文中 ...
- SQL海量数据读写性能优化
这是给某数据中心做的一个项目,项目难度之大令人发指,这个项目真正的让我感觉到了,商场如战场,而我只是其中的一个小兵,太多的战术,太多的高层之间的较量,太多的内幕了.具体这个项目的情况,我有空再写相关的 ...
- Windows下 bat调用TSql问题
一.建立sql文件 在sql管理工具中写好sql文件,并保证能够正常运行,之后用unique编码保存. 二.建立一个bat文件osql -U登录用户 -P密码 -S服务器 <sql文件.sql ...
- orcale开篇
1.数据库系统和数据库的管理系统 数据库系统=数据库的管理系统+oper操作员+硬件2.Oracle的版本 8i/ 9i 10g/11g 12c(cloud)3.实例和数据库的关系 实例:数据 ...
- ASP Session的功能的缺陷以及解决方案
转http://www.cnblogs.com/jhy55/p/3376925.html 目前ASP的开发人员都正在使用Session这一强大的功能,但是在他们使用的过程中却发现了ASP Sessio ...
- JAVA中数组介绍
一.数组: 数组指一组数据的集合,数组中的每个数据被称作元素. 二.数组定义: 数组类型[] 数组名 = new 数组类型[元素个数或数组长度]: (注意:等号前面的[]里面不能写任何东西) 也可以以 ...