码迷,mamicode.com
首页 > 编程语言 > 详细

python 常用函数

时间:2015-04-14 19:37:30      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

除法相关

  • 保留小数 

>>> from __future__ import division
>>> 5/3
1.6666666666666667
>>> 5/2
2.5

  •  求商、求余

>>> divmod(5, 2)
(2, 1)

  • 四舍五入

>>> round(5/2)
3.0

字符串相关

  • ord()能够返回某个字符所对一个的ASCII值(是十进制的),字符a在ASCII中的值是97,空格在ASCII中也有值,是32。

    反过来,根据整数值得到相应字符,可以使用chr()。

>>> ord(‘a‘)
97

>>> chr(99)
‘c‘

 编码问题

  • error---‘ascii‘ codec can‘t encode characters in position

>>> import sys
>>> sys.getdefaultencoding()
‘ascii‘

>>> sys.setdefaultencoding()

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
sys.setdefaultencoding()
AttributeError: ‘module‘ object has no attribute ‘setdefaultencoding‘
>>> reload(sys)
>>> sys.setdefaultencoding(‘utf-8‘)

 "AttributeError: ‘module‘ object has no attribute ‘setdefaultencoding‘"  why  ???

/Lib/site.py#l545:

"""Append module search paths for third-party packages to sys.path."""
* This module is automatically imported during initialization. *
def setencoding():  
  """Set the string encoding used by the Unicode implementation.
    The default is ‘ascii‘, but if you‘re willing to experiment, you can change this.
  """
  encoding = "ascii" # Default value set by _PyUnicode_Init()
def main():
  ......  
  # Remove sys.setdefaultencoding() so that users cannot change the
  # encoding after initialization. The test for presence is needed when
  # this module is run as a script, because this code is executed twice.
  if hasattr(sys, "setdefaultencoding"):
    del sys.setdefaultencoding
源码参见 https://hg.python.org/cpython/file/2.7/Lib/site.py#l545

编码问题更多可参考 http://www.the5fire.com/unicodeencodeerror-from-future.html



 

python 常用函数

标签:

原文地址:http://www.cnblogs.com/tangkaixin/p/4404668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!