python學習筆記(1 )__python

來源:互聯網
上載者:User

1、在確定自己不會匯入多個同名函數(從不同的模組匯入)的情況下,可以使用

from math import sqrt  【from 模組 import 函數】

這樣就可以直接使用sqrt(9),而不用每次都用math.sqrt(9)

2、可以使用變數來引用函數(及Python中的大多數對象),如

>>> import math>>> foo = math.sqrt>>> int(foo(16))4

3、原始字串,在要輸出的字串前加一個 r ,就不會進行轉義了(但是原始字串的最後一個字元不能是 \ ,除非對它轉義)

>>> print 'c:\now'c:ow>>> print r'c:\now'c:\now

4、分區,用於提取序列的一部分

>>> numbers = [1,2,3,4,5,6,7,8,9]>>> numbers[3:6][4, 5, 6]>>> numbers[0:1] #用[-3:-1]取得7、8    #用[-3:]取得最後三位[1]>>> numbers[::2]  #第三個數字為步長[1, 3, 5, 7, 9]>>> numbers[8:3:-2]#步長不能為0,但可以為負數[9, 7, 5]

5、索引

>>> "Hello"[1]    #[-1]得最後一個'o''e'>>> forth = raw_input("Year:")[3]Year:2008>>> forth'8'


6、in 成員資格,用in運算子檢測一個值是否在序列中

database = [['a','1234'],['b','0985'],['c','9527'],]username = raw_input("username:")pin = raw_input("pin:")if[username,pin] in database:    print "Access granted"

7、分區賦值

>>> name = list("he")>>> name['h', 'e']>>> name[1:] = list("is")>>> name['h', 'i', 's']>>> numbers = [1,5]>>> numbers[1:1] = [2,3,4]  #'替換'空的分區>>> numbers[1, 2, 3, 4, 5]>>> numbers[1:3]=[]#刪除>>> numbers[1, 4, 5]

8、列表的複製

y = x[ : ] , 不要用y=x,這樣x和y就指向同一個列表了

9、字串格式化

>>> s = "hello %s,%s python">>> values = ("I","HATE")<span style="white-space:pre"></span>#只有元組和字典可以格式化一個以上的值>>> print s % valueshello I,HATE python
10、模板字串


11、字串的translate函數

>>> from string import maketrans>>> table = maketrans("cs","kz")  #maketrans參數為兩個等長的字串,表示第一個字串中的每個字元都用第二個字串中相同位置的字元替換>>> len(table)256>>> table[97:123]'abkdefghijklmnopqrztuvwxyz'>>> maketrans("","")[97:123]<span style="white-space:pre"></span>#maketrans中包含了256個ASCII字元'abcdefghijklmnopqrstuvwxyz'>>> "this is a incredible test".translate(table)'thiz iz a inkredible tezt'

12、== 與 is

>>> x = y = [1,2,3]>>> z = [1,2,3]>>> x==yTrue>>> x is y<span style="white-space:pre"></span>#is是同一運算子,== 判斷兩個對象是否相等,is判斷是否等同(同一對象)True>>> x is zFalse


未完待續。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.