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
  1. def b64encode(s, altchars=None):
  2. """Encode a string using Base64.
  3.  
  4. s is the string to encode. Optional altchars must be a string of at least
  5. length 2 (additional characters are ignored) which specifies an
  6. alternative alphabet for the '+' and '/' characters. This allows an
  7. application to e.g. generate url or filesystem safe Base64 strings.
  8.  
  9. The encoded string is returned.
  10. """
  11. # Strip off the trailing newline
  12. encoded = binascii.b2a_base64(s)[:-1]
  13. if altchars is not None:
  14. return encoded.translate(string.maketrans(b'+/', altchars[:2]))
  15. return encoded
  1. def b64decode(s, altchars=None):
  2. """Decode a Base64 encoded string.
  3.  
  4. s is the string to decode. Optional altchars must be a string of at least
  5. length 2 (additional characters are ignored) which specifies the
  6. alternative alphabet used instead of the '+' and '/' characters.
  7.  
  8. The decoded string is returned. A TypeError is raised if s is
  9. incorrectly padded. Characters that are neither in the normal base-64
  10. alphabet nor the alternative alphabet are discarded prior to the padding
  11. check.
  12. """
  13. if altchars is not None:
  14. s = s.translate(string.maketrans(altchars[:2], '+/'))
  15. try:
  16. return binascii.a2b_base64(s)
  17. except binascii.Error, msg:
  18. # Transform this exception for consistency
  19. raise TypeError(msg)

b64decode源码

这里面的s是一个字符串类型的对象。

  1. import base64
  2.  
  3. s = 'Hello, python'
  4. b = base64.b64encode(s)
  5. print 'b为:', b
  6.  
  7. c = base64.b64decode(b)
  8. print 'c为:', c
  9.  
  10. # output
  11. b为: SGVsbG8sIHB5dGhvbg==
  12. c为: Hello, python
  • Python3
  1. def b64encode(s, altchars=None):
  2. """Encode the bytes-like object s using Base64 and return a bytes object.
  3.  
  4. Optional altchars should be a byte string of length 2 which specifies an
  5. alternative alphabet for the '+' and '/' characters. This allows an
  6. application to e.g. generate url or filesystem safe Base64 strings.
  7. """
  8. encoded = binascii.b2a_base64(s, newline=False)
  9. if altchars is not None:
  10. assert len(altchars) == 2, repr(altchars)
  11. return encoded.translate(bytes.maketrans(b'+/', altchars))
  12. return encoded
  1. def b64decode(s, altchars=None, validate=False):
  2. """Decode the Base64 encoded bytes-like object or ASCII string s.
  3.  
  4. Optional altchars must be a bytes-like object or ASCII string of length 2
  5. which specifies the alternative alphabet used instead of the '+' and '/'
  6. characters.
  7.  
  8. The result is returned as a bytes object. A binascii.Error is raised if
  9. s is incorrectly padded.
  10.  
  11. If validate is False (the default), characters that are neither in the
  12. normal base-64 alphabet nor the alternative alphabet are discarded prior
  13. to the padding check. If validate is True, these non-alphabet characters
  14. in the input result in a binascii.Error.
  15. """
  16. s = _bytes_from_decode_data(s)
  17. if altchars is not None:
  18. altchars = _bytes_from_decode_data(altchars)
  19. assert len(altchars) == 2, repr(altchars)
  20. s = s.translate(bytes.maketrans(altchars, b'+/'))
  21. if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
  22. raise binascii.Error('Non-base64 digit found')
  23. return binascii.a2b_base64(s)

b64decode源码

这里面的s是一个bytes对象,则字符串首先要经过编码encode()。经过b64encode/b64decode之后的返回结果也是bytes对象,所以我们要转换为Unicode对象就要再使用decode()方法去解码。

  1. import base64
  2.  
  3. s = 'Hello, Python!'
  4. b = base64.b64encode(s.encode('utf-8')).decode('utf-8')
  5. print(b)
  6.  
  7. c = base64.b64decode(b.encode('utf-8')).decode('utf-8')
  8. print(c)
  9.  
  10. # output
  11. SGVsbG8sIFB5dGhvbiE=
  12. Hello, Python!

python2与python3下的base64模块的更多相关文章

  1. python在Linux中安装虚拟环境,区别python2和python3,分别安装模块

    安装虚拟环境的时候遇到的问题,解决的过程很闹心,在这里简单直接的分享出来,就是为了解决问题.  安装虚拟环境(须在联网状态下) $ sudo pip install virtualenv $ sudo ...

  2. Python3下的paramiko模块

    paramiko模块是基于Python实现的SSH远程安全连接,用于SSH远程执行命令.文件传输等功能. 默认Python没有,需要手动安装:pip install paramiko SSH密码认证远 ...

  3. python2和python3中的编码问题

    开始拾起python,准备使用python3, 造轮子的过程中遇到了编码的问题,又看了一下python3和python2相比变化的部分. 首先说个概念: unicode:在本文中表示用4byte表示的 ...

  4. win10下python2与python3以及pip共存

    一 分别安装python2和python3 注意: 安装时记得勾选 Add Python.exe to Path 二 安装pip Python3最新版本有pip,无需安装 Python2: 下载pip ...

  5. win10下安装python2与python3以及pip共存

    一 分别安装python2和python3 注意: 安装时记得勾选 Add Python.exe to Path 二 安装pip Python3最新版本有pip,无需安装 Python2: 下载pip ...

  6. python2.7环境下的flask项目导入模块失败解决办法

    如下一个flask项目的目录: 这个flask项目在python3.6环境下可以正常启动,但是在python2.7环境下如下报错提示: 提醒模块找不到.如下解决方法: 只需要在views目录里面加一个 ...

  7. Windows下Python2与Python3两个版本共存的方法详解

    来源:http://www.jb51.net/article/105311.htm 这篇文章主要介绍了Windows下Python2与Python3两个版本共存的方法,文中介绍的很详细,对大家具有一定 ...

  8. python3下的IE自动化模块PAMIE

    PAMIE是Python下面的用于IE的自动化模块,支持python2和python3,python3的下载地址:http://sourceforge.net/projects/pamie/files ...

  9. Windows下安装python2与python3以及分别对应的virtualenv

    第三次装python2与python3 除此之外还学会了如何在命令行复制代码1.单击右键2.菜单中选择标记3.按住左键选中需要复制的内容4.松开左键5.单击右键 全局中python版本为python2 ...

随机推荐

  1. JPA规范基础 ppt教程

    https://wenku.baidu.com/view/5ca6ce6a1eb91a37f1115cee.html

  2. Java编程中中文乱码问题的研究及解决方案

    0 引言 Java最大的特性是与平台的无关性及开发环境的多样性.字符串被Java应用程序转化之前,是根据操作系统默认的编码方式编码.Java语言内部采用Unicode编码,它是定长双字节编码,即任何符 ...

  3. windows 安装python

    前言: Windows 中直接使用Python真的是心累 安装vs 2017(最好是最新版的, 因为python依赖于一些vs提供的包) 下载最新的python的安装程序 安装完毕之后, 不像Linu ...

  4. Spring注解之@Lazy注解,源码分析和总结

    一 关于延迟加载的问题,有次和大神讨论他会不会直接或间接影响其他类.spring的好处就是文档都在代码里,网上百度大多是无用功. 不如,直接看源码.所以把当时源码分析的思路丢上来一波. 二 源码分析 ...

  5. Invoke PowerShell by UiPath

    UiPath能够调用PowerShell ,最近在项目中得到了实践:  需求: 某系统生成的日志文件的名字,时间戳只到分,形如bz20180214_1655.log    这样在如果在1分钟内生成多个 ...

  6. MS Chart 条状图【转】

    private void Form1_Load(object sender, EventArgs e) {            string sql1 = "select  类别,coun ...

  7. 去除pycharm的波浪线

    PyCharm使用了较为严格的PEP8的检查规则,如果代码命名不规范,甚至多出的空格都会被波浪线标识出来,导致整个编辑器里铺满了波浪线,右边的滚动条也全是黄色或灰色的标记线,很是影响编辑.这里给大家分 ...

  8. hibernate课程 初探单表映射1-4 hibernate开发前准备

    开发前准备: 1 eclipse 2 hibernate tools的安装(需要相关的jar包)(可以简化orm框架) hibernate tools的安装步骤: 1 到官网下载 https://so ...

  9. AGC015 C Nuske vs Phantom Thnook(前缀和)

    题意 题目链接 给出一张$n \times m$的网格,其中$1$为蓝点,$2$为白点. $Q$次询问,每次询问一个子矩阵内蓝点形成的联通块的数量 保证任意联通块内的任意蓝点之间均只有一条路径可达 S ...

  10. Catch the moments of your life. Catch them while you're young and quick.

    Catch the moments of your life. Catch them while you're young and quick.趁你还年轻利落,把握住生活中的美好瞬间吧!