python學習筆記 02

2021-09-18 00:25:09 字數 2426 閱讀 1821

f = file('m.txt', 'r')

for line in f.readlines():

line = line.strip('\n').split(':')

print line #print 可以列印字串也可以列印list

print abc,     這樣可以不換行

f.read 方法可以處理一種特殊情況,當f.read讀到檔案結尾時,如果檔案在結尾增加內容,再次f.read()則可以讀取剛才增加的內容

string.zfill(width) 返回乙個長度為width的string,不足左邊補0

str + str2   連線

str * 4 重複

str[1:4] 擷取

「h" in str 成員運算子 - 如果字串中包含給定的字元返回 true

"my name is %s and weight is %d kg!" % ('zara', 21)  格式化

str.capitalize  首字元大寫

str.center(width)返回乙個str居中,長度為width,左右用0填充的字串

str.count(xx) 返回子串xx在str**現的次數

str.decode('utf-8') 以 encoding 指定的編碼格式utf-8 解碼 string

str.encode('utf-8')  以encoding指定的編碼格式utf-8編碼str

列表就是c中的陣列,php中的無key陣列

list.count(x) 統計某個元素在列表**現的次數

list.extend(list2) 在列表結尾追加一組元素list2

list.index(x) 在列表中找出x第一次出現的位置

list.insert(index, x) 插入元素

list.pop(index=-1)移除乙個元素,並返回,預設最後乙個

list.remove(obj) 移除列表中某個值的第乙個匹配項

list.reverse 倒排

list.sort 排序 按值的字典排序

len(list) 返回長度

list + list2 組合

list * 4    返回乙個重複4次list的元素的 list

x in list 返回true 或 false

for i in list: print i    遍歷

list(tuple) 把元組list 轉換為列表

元組是一種常量陣列

tuple = (1, 2, 3)

刪除元組   del tuple

tuple(x) 把列表x 轉換為元組

任意無符號的物件,以逗號隔開,預設為元組,     print 1,2,3

字典是可變容器   x =

訪問字典    print    x['a'],修改   x['a'] = 'bbbbb'

刪除元素 del x['a']       刪除字典 del x

cmp(dict1, dict2) 比較

len(dict) 計算長度

str(dict) 輸出字典的字串表示

dict.clear() 清空字典

dict.copy() 淺複製

dict.fromkeys(seq, val) 建立乙個新字典,key為seq中的key,值統一為val

dict.get(key)返回指定的值 

dict.has_key 如果鍵在字典dict裡返回true,否則返回false

dict.items() 返回乙個二維列表,每個元素是乙個子列表[key,value]

dict.keys() 返回乙個列表,包含dict所有的key

遍歷     for i in list:   #只會遍歷key, 效率高       for k,v list.items() :   同時遍歷

dict.values() 返回所有的value

dict.pop(key) 刪除指定的key,返回對應的值 

dict.popitem() 隨機刪除並返回一組key,value

定義集合   x =    x = set(['a', 'b', 'a', 'b'])

x.add('c')為集合新增乙個元素

x.clear 清空集合

x.copy 複製乙個集合

x.difference()返回多個集合的差集

x.difference_update(y) 移除集合中的元素,這些元素在y集合中也存在

x.discard(y) 刪除乙個元素

x.intersection(y) 交集

x.pop 隨機移除乙個元素

x.remove(y) 如果y存在則移除,不存在則報錯

x.union(y) 並集

x.update(y) 給集合x新增元素,y是乙個集合

python學習筆記 02

1.裝飾器 裝飾器def def inner args,kwargs return func args,kwargs return inner deffunc pass view code 裝飾器from functools import wraps def wraps func def inner...

學習《流暢的Python學習》 筆記02

1.2.2 字串表示形式 python 有乙個內建的函式叫 repr,它能把乙個物件用字串的形式表 達出來以便辨認,這就是 字串表示形式 repr 就是通過repr這個特殊方法來得到乙個物件的字串表示形式的。如果沒有實現repr,當我們在控制台裡列印乙個向量的例項時,得到的字串 可能會是 互動式控制...

Python3學習筆記02

昨天發現無法轉碼,於是就又找了另外找了乙個參考 發現可以執行了 encoding utf 8 import urllib.request def getdata url www.xx.com data urllib.request.urlopen url read z data data.decod...