string 类型

参考: A Guide to Unicode, UTF-8 and Strings in Python | by Sanket Gupta | Towards D…

python2 有两种 string 类型

  • str
  • unicode

转换关系: str — decode –> unicode

unicode –> encode –> str

str 类型

  • 默认使用 ascii 编码
  • 类似 c/c++, 本身实际上无编码, string literal 编码类型由代码文件的编码决定

str.decode

  • 语法: str.decode('coding-name')
  • 返回值类型: <type 'unicode'>

str.encode

  • 返回值类型: <type 'str'>

unicode 类型

  • 默认使用 unicode 解码格式

unicode.encode()

  • 返回值类型: <type 'str'>

FAQ

打印输出和 string literal 不一致问题

确保 console (terminal) 的编码和 python source code 编码一致

中文编码:

1
2
3
4
5
# -*- coding: gb2312; -*-
from __future__ import print_function

simple = u'中'
print(simple)

注:

  • 上述代码在 windows chcp 936 可以正常输出 '中'
  • 在 windows chcp 65001 输出异常
  • 类似

    source: gb2312
    
    cmd chcp 936 --> 正常
    cmd chcp 65001 --> 异常
    ---------------------------
    source: utf-8
    
    cmd chcp 936 --> 异常
    cmd chcp 65001 --> 正常
    

str.decode 失败问题

str 实际的编码是 source code file 的编码格式,因此,如果使用和 source code file 编码格式不一致,大机率失败

例如:

  • source code: gb2312

    • 失败例子

      1
      2
      
      value = '中国'
      value.decode('utf-8')
    • 成功例子

      1
      2
      
      value = '中国'
      value.decode('gb2312')

json unicode 转 str 方法