python 常用函數

來源:互聯網
上載者:User

標籤:

除法相關
  • 保留小數 

>>> 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 常用函數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.