30-python3 中 bytes 和 string 之间的互相转换

转自:http://www.jb51.net/article/105064.htm

password = b'123456'

等价于:

pw = '123456'
password = pw.encode(encoding='utf-8')

  

前言

Python 3 最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是 Unicode,由 str 类型表示,二进制数据则由 bytes 类型表示。Python 3 不会以任意隐式的方式混用 str 和 bytes,正是这使得两者的区分特别清晰。你不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也不能将字符串传入参数为字节包的函数(反之亦然).

python3.0 中怎么创建 bytes 型数据

  1.  
    >>> bytes([1,2,3,4,5,6,7,8,9])
  2.  
    >>> bytes("python", 'ascii') # 字符串,编码

首先来设置一个原始的字符串,

  1.  
    >>> website = 'http://www.jb51.net/'
  2.  
    >>> type(website)
  3.  
    <class 'str'>
  4.  
    >>> website
  5.  
    'http://www.jb51.net/'

按 utf-8 的方式编码,转成 bytes

  1.  
    >>> website_bytes_utf8 = website.encode(encoding="utf-8")
  2.  
    >>> type(website_bytes_utf8)
  3.  
    <class 'bytes'>
  4.  
    >>> website_bytes_utf8
  5.  
    b'http://www.jb51.net/'

按 gb2312 的方式编码,转成 bytes

  1.  
    >>> website_bytes_gb2312 = website.encode(encoding="gb2312")
  2.  
    >>> type(website_bytes_gb2312)
  3.  
    <class 'bytes'>
  4.  
    >>> website_bytes_gb2312
  5.  
    b'http://www.jb51.net/'

解码成 string,默认不填

  1.  
    >>> website_string = website_bytes_utf8.decode()
  2.  
    >>> type(website_string)
  3.  
    <class 'str'>
  4.  
    >>> website_string
  5.  
    'http://www.jb51.net/'

解码成 string,使用 gb2312 的方式

  1.  
    >>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")
  2.  
    >>> type(website_string_gb2312)
  3.  
    <class 'str'>
  4.  
    >>> website_string_gb2312
  5.  
    'http://www.jb51.net/'