1. 程式人生 > >str 和 list 的共性和list的方法

str 和 list 的共性和list的方法

都可以切片

test = 'abcdefghijklmn'
print (test[1:9:3])

輸出:
beh

都可以索引:

test = 'abcdefghijklmn'
print (test[-4])

輸出:
k

都是可迭代物件:

test = 'abcde'
for n in test:
    print (n)

輸出:
a
b
c
d
e

都可以用in或者not in 來判斷:

test = ['a', 'b', 'c', 'd', 'e']
v = 'a' in test
print(v)

test = 'abcde'
v = 'a' in test
print(v)

輸出:
True
True

都可以修改,但是方式不同:

str修改是重新建立新的str,用replace(),join(),split(),strip()等:

test = 'bbbbbbbbbb'
p = test.replace('b','2',5)  #共替換5次
print(p)

輸出:
22222bbbbb

實現刪除字元效果:

test = 'abcde'
p = test.replace('b','')
print(p)

輸出:
acde

實現比join()前後多一個字元的效果:

test = 'abcde'
p = test.replace('','-')
print(p)

輸出:
-a-b-c-d-e-

list修改是原來的列表上修改

用索引替換物件:

test = ['a','b','c','d','e']
test[-1] = 'k'       
print(test)

輸出:
[‘a’, ‘b’, ‘c’, ‘d’, ‘k’]

用切片替換物件:

test = ['a','b','c','d','e']
test[1:3] = [1,2]    
print(test)

輸出:
[‘a’, 1, 2, ‘d’, ‘e’]

del刪除索引指定的物件:

test = ['a', 'b', 'c', 'd', 'e']  
del test[0]                                #刪除索引指定的物件
print(test)

test = ['a','b','c','d','e']
del test[1:4]                             #刪除切片指定的物件
print(test)

輸出:
[‘b’, ‘c’, ‘d’, ‘e’]
[‘a’, ‘e’]

remove()從列表左邊開始刪除第一個指定的值:

test = ['a','b','a','d','e']
test.remove('a')        
print(test)

輸出:
[‘b’, ‘a’, ‘d’, ‘e’]

pop()彈出序列末尾的值並賦值給v:

test = ['a','b','c','d','e']
v = test.pop()        
print(v,test)

輸出:
e [‘a’, ‘b’, ‘c’, ‘d’]

pop()彈出索引指定的值並賦值給v:

 test = ['a','b','c','d','e']
v = test.pop(0)      
print(v,test)

輸出:
a [‘b’, ‘c’, ‘d’, ‘e’]

appden()在序列末尾加入某一個元素,引數為單一物件:

test1 = ['a', 'b', 12]
test1.append(['cd',34])
print(test1)

輸出:
[‘a’, ‘b’, 12, [‘cd’, 34]]

extend()在序列末尾增加一系列元素,引數為可迭代物件:

test1 = ['a', 'b', 12]
test1.extend(['cd',34])
print(test1)

輸出:
[‘a’, ‘b’, 12, ‘cd’, 34]

insert在索引指定的位置插入物件:

test = ['a','b','c','d','e']
test.insert(0,'sss')   
print(test)

輸出:
[‘sss’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

sort()給序列永久性排序:

test = ['D','a','我','1','大','B','d','愛','3','c','4','家','b','2','A','C']
test.sort()
print(test)

輸出:
[‘1’, ‘2’, ‘3’, ‘4’, ‘A’, ‘B’, ‘C’, ‘D’, ‘a’, ‘b’, ‘c’, ‘d’, ‘大’, ‘家’, ‘我’, ‘愛’]

sort(reverse=True)給序列永久性反向排序:

test = ['D','a','我','1','大家','B','d','愛','3','c','4','b','2','A','C']
test.sort(reverse = True)
print(test)

輸出:
[‘愛’, ‘我’, ‘大家’, ‘d’, ‘c’, ‘b’, ‘a’, ‘D’, ‘C’, ‘B’, ‘A’, ‘4’, ‘3’, ‘2’, ‘1’]

sorted()將序列臨時排序:

test = ['e','b','f','a','c']
v = sorted(test)
print(v)

輸出:
[‘a’, ‘b’, ‘c’, ‘e’, ‘f’]

reverse()將序列永久性反轉順序:

test = ['家','b','2','A','C']
test.reverse()
print(test)

輸出:
[‘C’, ‘A’, ‘2’, ‘b’, ‘家’]

clear()清空列表:

test1 = ['a', 'b', 12]
test1.clear()
print(test1)

輸出:
[]

copy()淺拷貝:

test1 = ['a', 'b', 12]
v = test1.copy()
print(v)

輸出:
[‘a’, ‘b’, 12]

count()計算元素的次數:

test1 = ['a', 'b','a', 12]
v = test1.count('a')
print(v)

輸出:
2

index()從左邊開始根據值找到對應索引,沒找到會報錯:

test1 = ['a', 'b', 12,'b']
v = test1.index('b')
print(v)

輸出:
1