python列表字串集合常用方法

2022-05-13 20:11:59 字數 2895 閱讀 4266

1.2 字串常用方法

# 1. find方法可以在乙個較長的字串中查詢子串,他返回子串所在位置的最左端索引,如果沒有找到則返回-1

a = 'abcdefsdada'

print(a.find('abc')) # the result : 0

print(a. find('abc',10,100)) # the result : 11 指定查詢的起始和結束查詢位置

​# 2. join方法是非常重要的字串方法,他是split方法的逆方法,用來連線序列中的元素並且需要需要被連線的元素都必須是字串。

a = ['1','2','3']

print('+',join(a)) # the result : 1+2+3

​# 3. split方法,是乙個非常重要的字串,他是join的逆方法,用來將字串分割成序列

print('1+2+3+4'.spkit('+')) # the result : ['1','2','3','4']

​# 4. strip 方法返回去除收尾空格(不包括內部)的字串

print(" test test ".strip()) #the result :「test test」

​# 5. replace 方法返回某字串所有匹配項均勻被替換之後得到字串

print("this is a test".replace('is','is_test')) #the result : this_test is_test a test

1.3 字串常用方法

# 1. clear方法清除字典中所有的項, 這是乙個原地操, 所有無返回值(或者說返回none)

d =

d.clear()

print(d) #the result : {}

​# 2. fromkeys方法使用給定的鍵建立新的字典,每個鍵都對應乙個預設的值none

print({}.fromkeys(['name','age'])) #the result : 

# 3. get方法是個更寬鬆的訪問字典想的方法,如果試圖訪問字典中不存在的項時不會報錯僅會 返回: none

d =

print(d.get('tom')) #the result : 8777

print(d.get('not_exist')) #the result : none

​# 4. for 迴圈字典有三種方法

d =

for k,v in d.items():

print(k,v)

for k in d.values():

print(k)

for k in d.keys():

print(k)

​# 5. pop 方法用於獲得對應與給定鍵的值,然後將這個「鍵-值」對從字典中移除

d =

v = d.pop('tom')

print(v) #8777

​# 6. setdefault方法在某種程度上類似與get方法,能夠獲得與給定鍵相關聯的值,除此之外,setdefault還能再字典中不含有給定鍵的情況下設定相應的鍵值

d =

d.setdefault('tom') #the result : 8777

print(d.setdefault('test')) #the result : none

print(d) #

​# 7. update方法可以利用乙個字典項更新另乙個字典,提供的字典中的項會被新增到舊的字典中,如果相同的鍵則會被覆蓋

d =

a =

d.update(a)

print(d) #the result :

​# 8. 將兩個列表組合成字典

keys = ['a', 'b']

values = [1, 2]

print(dict(zip(keys,values))) #

1.4 集合常用方法

list_1 = [1,2,3,4,5,1,2]

#1、去重(去除list_1中重複元素1,2)

list_1 = set(list_1) #去重:

print(list_1)

list_2 = set([4,5,6,7,8])

​#2、交集(在list_1和list_2中都有的元素4,5)

print(list_1.intersection(list_2)) #交集:

​#3、並集(在list_1和list_2中的元素全部列印出來,重複元素僅列印一次)

print(list_1.union(list_2)) #並集:

​#4、差集

print(list_1.difference(list_2)) #差集:在list_1中有在list_2中沒有:

print(list_2.difference(list_1)) #差集:在list_1中有在list_2中沒有:

python 基礎 列表,字串

url www.woaixuexi.com 1.替換 url.replace com cn print url 輸出 www.woaixuexi.cn 2.判斷是否以某個字段開頭 url.startswith www 返回 true 同startswith url.endwith com 3.查某個...

Python列表 字串 字典等常用操作

字典 len 字典 獲取字典的鍵值對數量 字典.keys 所有key列表 字典.values 所有value列表 字典.items 所有 key,value 元組列表 字典.pop key 刪除指定鍵值對,key不存在會報錯 字典.popitem 隨機刪除乙個鍵值對 字典.clear 清空字典 字典...

Python字串 列表 字典 元組 集合

print ord 我 ord 喜 ord 歡 ord 你 25105 21916 27426 20320 print chr 25105 chr 21916 chr 27426 chr 20320 我 喜 歡 你 使用insert 函式在指定位置插入元素,其接受兩個引數,第乙個引數指定要插入的位置...