python資料型別(string/list/tuple/dict)內建方法
Python 字串常用方法總結
明確:對字串的操作方法都不會改變原來字串的值
1,去掉空格和特殊符號
name.strip() 去掉空格和換行符
name.strip('xx') 去掉某個字串
name.lstrip() 去掉左邊的空格和換行符
name.rstrip() 去掉右邊的空格和換行符
2,字串的搜尋和替換
name.count('x') 查詢某個字元在字串裡面出現的次數
name.capitalize() 首字母大寫
name.center(n,'-') 把字串放中間,兩邊用- 補齊
name.find('x') 找到這個字元返回下標,多個時返回第一個;不存在的字元返回-1
name.index('x') 找到這個字元返回下標,多個時返回第一個;不存在的字元報錯
name.replace(oldstr, newstr) 字串替換
name.format() 字串格式化
name.format_map(d) 字串格式化,傳進去的是一個字典
Year {} Rs. {:.2f}".format(year, value) 稱為字串格式化,大括號和其中的字元會被替換成傳入 str.format() 的引數,也即 year 和 value。其中 {:.2f} 的意思是替換為 2 位精度的浮點數。
{:5d} 的意思是替換為 5 個字元寬度的整數,寬度不足則使用空格填充。
divmod(num1,num2)返回一個元組,這個元組包含兩個值,第一個是num1 與 num2 相整除得到的值,第二個是num1 與 num2 求餘得到的值
用 * 運算子查封這兩個元組,得到這兩個值。
等價於
3,字串的測試和替換函式
S.startswith(prefix[,start[,end]])
#是否以prefix開頭
S.endswith(suffix[,start[,end]])
#以suffix結尾
S.isalnum()
#是否全是字母和數字,並至少有一個字元
S.isalpha() #是否全是字母,並至少有一個字元
S.isdigit() #是否全是數字,並至少有一個字元
S.isspace() #是否全是空白字元,並至少有一個字元
S.islower() #S中的字母是否全是小寫
S.isupper() #S中的字母是否便是大寫
S.istitle() #S是否是首字母大寫的
4,字串的分割
name.split() 預設是按照空格分割
name.split(',') 按照逗號分割
5,連線字串
‘,’.join(slit) 用逗號連線slit 變成一個字串,slit 可以是字元,列表,字典(可迭代的物件)
int 型別不能被連線
6,擷取字串(切片)
str = '0123456789′
print str[0:3] #擷取第一位到第三位的字元
print str[:] #擷取字串的全部字元
print str[6:] #擷取第七個字元到結尾
print str[:-3] #擷取從頭開始到倒數第三個字元之前
print str[2] #擷取第三個字元
print str[-1] #擷取倒數第一個字元
print str[::-1] #創造一個與原字串順序相反的字串
print str[-3:-1] #擷取倒數第三位與倒數第一位之前的字元
print str[-3:] #擷取倒數第三位到結尾
print str[:-5:-3] #逆序擷取
7.string 模組
import string
string.ascii_uppercase 所有大寫字母
string.ascii_lowercase 所有小寫字母
string.ascii_letters 所有字母
string.digits 所有數字
python列表的常用操作方法小結
1.建立列表。只要把逗號分隔的不同的資料項使用方括號括起來即可
List = ['wade','james','bosh','haslem']
與字串的索引一樣,列表索引從0開始。列表可以進行擷取、組合等
2.新增新的元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
3.遍歷列表
1 2 |
|
4.訪問列表中的值
使用下標索引來訪問列表中的值,同樣你也可以使用方括號的形式擷取字元,如下所示:
1 2 3 |
|
5.從list刪除元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
6.排序和反轉程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
7.Python列表擷取
Python的列表擷取與字串操作型別相同,如下所示:
L = ['spam', 'Spam', 'SPAM!']
操作:
1 2 3 4 |
|
8.Python列表操作的函式和方法
列表操作包含以下函式:
1、cmp(list1, list2):比較兩個列表的元素 (python3已丟棄)
2、len(list):列表元素個數
3、max(list):返回列表元素最大值
4、min(list):返回列表元素最小值
5、list(seq):將元組轉換為列表
列表操作常用操作包含以下方法:
1、list.append(obj):在列表末尾新增新的物件
2、list.count(obj):統計某個元素在列表中出現的次數
3、list.extend(seq):在列表末尾一次性追加另一個序列中的多個值(用新列表擴充套件原來的列表)
4、list.index(obj):從列表中找出某個值第一個匹配項的索引位置
5、list.insert(index, obj):將物件插入列表
6、list.pop(obj=list[-1]):移除列表中的一個元素(預設最後一個元素),並且返回該元素的值
7、list.remove(obj):移除列表中某個值的第一個匹配項
8、list.reverse():反向列表中元素
9、list.sort([func]):對原列表進行排序
Python 元組(Tuple)操作詳解
一、tuple也是一個class,是不可變的list型別,不可以增刪改。
建立:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
訪問:(與list一樣)tup1[1:5];
修改:不可以修改,只能增加新的部分;
tup3 = tup1 + tup2;
print tup3;
二、任意無符號的物件,以逗號隔開,預設為元組,如下例項:
a=1,2,3,'e'
a=(1,2,3,'e').
三、Python元組包含了以下內建函式(與list差不多的函式)
1、cmp(tuple1, tuple2):比較兩個元組元素。
2、len(tuple):計算元組元素個數。
3、max(tuple):返回元組中元素最大值。
4、min(tuple):返回元組中元素最小值。
5、tuple(seq):將列表轉換為元組。
四、tuple的方法:
1、count():查詢元素在tuple中出現的次數。
2.index():查詢元素的第一個索引值。
五、Tuple 是不可變 list。 一旦建立了一個 tuple 就不能以任何方式改變它。
①、Tuple 與 list 的相同之處
定義 tuple 與定義 list 的方式相同, 除了整個元素集是用小括號包圍的而不是方括號。
Tuple 的元素與 list 一樣按定義的次序進行排序。 Tuples 的索引與 list 一樣從 0 開始, 所以一個非空 tuple 的第一個元素總是 t[0]。
負數索引與 list 一樣從 tuple 的尾部開始計數。
與 list 一樣分片 (slice) 也可以使用。注意當分割一個 list 時, 會得到一個新的 list ;當分割一個 tuple 時, 會得到一個新的 tuple。
②、Tuple 不存在的方法
您不能向 tuple 增加元素。Tuple 沒有 append 或 extend 方法。
您不能從 tuple 刪除元素。Tuple 沒有 remove 或 pop 方法。
然而, 您可以使用 in 來檢視一個元素是否存在於 tuple 中。
③、用 Tuple 的好處
Tuple 比 list 操作速度快。如果您定義了一個值的常量集,並且唯一要用它做的是不斷地遍歷它,請使用 tuple 代替 list。
如果對不需要修改的資料進行 “防寫”,可以使程式碼更安全。使用 tuple 而不是 list 如同擁有一個隱含的 assert 語句,說明這一資料是常量。如果必須要改變這些值,則需要執行 tuple 到 list 的轉換。
④、Tuple 與 list 的轉換
Tuple 可以轉換成 list,反之亦然。內建的 tuple 函式接收一個 list,並返回一個有著相同元素的 tuple。而 list 函式接收一個 tuple 返回一個 list。從效果上看,tuple 凍結一個 list,而 list 解凍一個 tuple。
python的字典常用方法
字典是一種通過名字或者關鍵字引用的得資料結構,其鍵可以是數字、字串、元組,這種結構型別也稱之為對映。字典型別是Python中唯一內建的對映型別,基本的操作包括如下:
(1)len():返回字典中鍵—值對的數量;
(2)d[k]:返回關鍵字對於的值;
(3)d[k]=v:將值關聯到鍵值k上;
(4)del d[k]:刪除鍵值為k的項;
(5)key in d:鍵值key是否在d中,是返回True,否則返回False。
一、字典的建立
1.1 直接建立字典
d={'one':1,'two':2,'three':3}
print d
print d['two']
print d['three']
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
2
3
>>>
1.2 通過dict建立字典
# _*_ coding:utf-8 _*_
items=[('one',1),('two',2),('three',3),('four',4)]
print u'items中的內容:'
print items
print u'利用dict建立字典,輸出字典內容:'
d=dict(items)
print d
print u'查詢字典中的內容:'
print d['one']
print d['three']
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
items中的內容:
[('one', 1), ('two', 2), ('three', 3), ('four', 4)]
利用dict建立字典,輸出字典內容:
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
查詢字典中的內容:
1
3
>>>
或者通過關鍵字建立字典
# _*_ coding:utf-8 _*_
d=dict(one=1,two=2,three=3)
print u'輸出字典內容:'
print d
print u'查詢字典中的內容:'
print d['one']
print d['three']
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
輸出字典內容:
{'three': 3, 'two': 2, 'one': 1}
查詢字典中的內容:
1
3
>>>
二、字典的格式化字串
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
print d
print "three is %(three)s." %d
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
three is 3.
>>>
三、字典方法
3.1 clear函式:清除字典中的所有項
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
print d
d.clear()
print d
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
{}
>>>
請看下面兩個例子
3.1.1
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
print dd
d={}
print d
print dd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two': 2, 'one': 1}
{}
{'two': 2, 'one': 1}
>>>
3.1.2
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
print dd
d.clear()
print d
print dd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two': 2, 'one': 1}
{}
{}
>>>
3.1.2與3.1.1唯一不同的是在對字典d的清空處理上,3.1.1將d關聯到一個新的空字典上,這種方式對字典dd是沒有影響的,所以在字典d被置空後,字典dd裡面的值仍舊沒有變化。但是在3.1.2中clear方法清空字典d中的內容,clear是一個原地操作的方法,使得d中的內容全部被置空,這樣dd所指向的空間也被置空。
3.2 copy函式:返回一個具有相同鍵值的新字典
# _*_ coding:utf-8 _*_
x={'one':1,'two':2,'three':3,'test':['a','b','c']}
print u'初始X字典:'
print x
print u'X複製到Y:'
y=x.copy()
print u'Y字典:'
print y
y['three']=33
print u'修改Y中的值,觀察輸出:'
print y
print x
print u'刪除Y中的值,觀察輸出'
y['test'].remove('c')
print y
print x
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
初始X字典:
{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}
X複製到Y:
Y字典:
{'test': ['a', 'b', 'c'], 'one': 1, 'three': 3, 'two': 2}
修改Y中的值,觀察輸出:
{'test': ['a', 'b', 'c'], 'one': 1, 'three': 33, 'two': 2}
{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}
刪除Y中的值,觀察輸出
{'test': ['a', 'b'], 'one': 1, 'three': 33, 'two': 2}
{'test': ['a', 'b'], 'three': 3, 'two': 2, 'one': 1}
>>>
注:在複製的副本中對值進行替換後,對原來的字典不產生影響,但是如果修改了副本,原始的字典也會被修改。deepcopy函式使用深複製,複製其包含所有的值,這個方法可以解決由於副本修改而使原始字典也變化的問題。
# _*_ coding:utf-8 _*_
from copy import deepcopy
x={}
x['test']=['a','b','c','d']
y=x.copy()
z=deepcopy(x)
print u'輸出:'
print y
print z
print u'修改後輸出:'
x['test'].append('e')
print y
print z
運算輸出:
輸出:
{'test': ['a', 'b', 'c', 'd']}
{'test': ['a', 'b', 'c', 'd']}
修改後輸出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'test': ['a', 'b', 'c', 'd', 'e']}
{'test': ['a', 'b', 'c', 'd']}
>>>
3.3 fromkeys函式:使用給定的鍵建立新的字典,鍵預設對應的值為None
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'])
print d
運算輸出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': None, 'two': None, 'one': None}
>>>
或者指定預設的對應值
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'],'unknow')
print d
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 'unknow', 'two': 'unknow', 'one': 'unknow'}
>>>
3.4 get函式:訪問字典成員
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.get('one')
print d.get('four')
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
1
None
>>>
注:get函式可以訪問字典中不存在的鍵,當該鍵不存在是返回None
3.5 has_key函式:檢查字典中是否含有給出的鍵
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.has_key('one')
print d.has_key('four')
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
True
False
>>>
3.6 items和iteritems函式:items將所有的字典項以列表方式返回,列表中項來自(鍵,值),iteritems與items作用相似,但是返回的是一個迭代器物件而不是列表
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
list=d.items()
for key,value in list:
print key,':',value
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
three : 3
two : 2
one : 1
>>>
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
it=d.iteritems()
for k,v in it:
print "d[%s]="%k,v
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
d[three]= 3
d[two]= 2
d[one]= 1
>>>
3.7 keys和iterkeys:keys將字典中的鍵以列表形式返回,iterkeys返回鍵的迭代器
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print u'keys方法:'
list=d.keys()
print list
print u'\niterkeys方法:'
it=d.iterkeys()
for x in it:
print x
運算結果:
{'three': 3, 'two': 2, 'one': 1}
keys方法:
['three', 'two', 'one']
iterkeys方法:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
three
two
one
>>>
3.8 pop函式:刪除字典中對應的鍵
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.pop('one')
print d
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
{'three': 3, 'two': 2}
>>>
3.9 popitem函式:移出字典中的項
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.popitem()
print d
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
{'two': 2, 'one': 1}
>>>
3.10 setdefault函式:類似於get方法,獲取與給定鍵相關聯的值,也可以在字典中不包含給定鍵的情況下設定相應的鍵值
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.setdefault('one',1)
print d.setdefault('four',4)
print d
運算結果:
{'three': 3, 'two': 2, 'one': 1}
1
4
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
>>>
3.11 update函式:用一個字典更新另外一個字典
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3
}
print d
x={'one':1}
d.update(x)
print d
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 123}
{'three': 3, 'two': 2, 'one': 1}
>>>
3.12 values和itervalues函式:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由於在字典中值不是唯一的,所以列表中可以包含重複的元素
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3,
'test':2
}
print d.values()
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
[2, 3, 2, 123]
>>>