lang110 发表于 2015-4-24 06:14:07

python技巧31[python文件的encoding和str的decode]

  
  一 python文件的encoding
  默认地,python的.py文件以标准的7位ASCII码存储,然而如果有的时候用户需要在.py文件中包含很多的unicode字符,例如.py文件中需要包含中文的字符串,这时可以在.py文件的第一行或第二行增加encoding注释来将.py文件指定为unicode格式。
  #!/usr/bin/env python
# -*- coding: UTF-8 -*-
s = "中国" # String in quotes is directly encoded in UTF-8.
  
  
  但是如果你的py文件是文本文件,且是unicode格式的,不指定# -*- coding: UTF-8 -*-也可以的。
  (通过notepad++下的format->encode in utf-8来确保为utf-8)
  如下:


import sys
print (sys.getdefaultencoding())
mystr = "test unicode 中国"
print (mystr)  
   还有奇怪的是好像sys.getdefaultencoding()总是返回utf-8,不管文件是ascii还是utf8的。
  
  可以使用下面的设置python文件编码:
  #encoding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
  
  二 str的encode
  在python3以后的版本中,str默认已经为unicode格式。当然也可以使用b''来定义bytes的string。
  但是有的时候我们需要对str进行ASCII和Unicode间转化,unicode的str的转化bytes时使用str.encode(),bytes的str转化为unicode时使用str.decode()。
  
  python2和python3中str的比较:

  
  python3中的str的转化函数:

  
  可能需要str的转化的情况:

  
  可能需要str的转化的情况:

  
  完!
页: [1]
查看完整版本: python技巧31[python文件的encoding和str的decode]