首页 > 编程语言 > 详细

python 常用函数

时间:2015-04-14 19:34:33      阅读:240      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!