這裏總結了平時寫腳本時經常用到的一些基礎方法,做個記錄
1、split()函數
分隔符
將字符串分割成由若干子串
組成的列表
str.split(str="", num=string.count(str))
str -- 分隔符,默認爲所有的空字符,包括空格、換行(\n)、製表符(\t)等。
num -- 分割次數。默認爲 -1, 即分隔所有。
默認全部分割
>>> case = "happy, new, year"
>>> case.split(',')
['happy', ' new', ' year']
指定分割次數(如下分割1次,分成2個列表)
>>> txt = "Google#Runoob#Taobao#Facebook"
>>> txt.split("#", 1)
['Google', 'Runoob#Taobao#Facebook']
>>> test = "my name is xxx yyy"
>>> test.split()
['my', 'name', 'is', 'xxx', 'yyy']
默認是以空格作爲分隔符,不管空格在哪,或者有幾個,全部被切掉了
分享一篇文我認爲解釋最形象的文章:python 字符串的split()函數詳解
2、join()函數
指定的字符
連接生成一個新的字符串
>>> case = ['a', 'b', 'c']
>>> ','.join(case) # 以','連接
'a,b,c'
>>> ''.join(case) # 以空字符連接
'abc'
>>> ' '.join(case) # 以單個空格符連接
'a b c'
3、replace()函數
max
,則替換不超過 max
次語法
str.replace(old, new[, max])
old -- 將被替換的子字符串。
new -- 新字符串,用於替換old子字符串。
max -- 可選字符串, 替換不超過 max 次
>>> strs = "this is string example....wow!!! this is really string";
>>> strs.replace("is", "was")
'thwas was string example....wow!!! thwas was really string'
>>> strs.replace("is", "was", 2);
'thwas was string example....wow!!! this is really string'
4、remove()函數
語法:
list.remove(obj)
參數
obj -- 列表中要移除的對象
>>> test = ["a","b","a","c","a"]
>>> test.remove("a")
>>> test
['b', 'a', 'c', 'a']
5、del()函數
指定位置
的元素,在刪除時需要指定元素的索引位置
>>> cat = ["胖喵","橘喵","奶牛喵"]
>>> del cat[1]
>>> cat
['胖喵', '奶牛喵']
往前移動
填補空出的位置,且列表長度
減 1。>>> test = ["a","b","c","d","e","f"]
>>> del test[0:3] # 刪除列表中前3個元素
>>> test
['d', 'e', 'f']
結合index()
函數刪除某個元素(用index()獲取元素位置,然後用del()刪除該元素)
>>> test = ["a","b","c","d","e","f"]
>>> del test[test.index("a")]
>>> test
['b', 'c', 'd', 'e', 'f']
6、pop()函數
pop()
同樣可以獲取列表中指定位置的元素,但在獲取完成後,該元素會被自動刪除;pop()
指定了偏移量
,它會返回偏移量對應位置
的元素;-1
pop(0)
將返回列表的頭元素
,而pop()
或 pop(-1)
則會返回列表的尾元素
>>> test = ["a","b","c","d","e","f"]
>>> test.pop()
'f'
>>> test
['a', 'b', 'c', 'd', 'e']
>>> test = ["a","b","c","d","e","f"]
>>> test.pop(2)
'c'
>>> test
['a', 'b', 'd', 'e', 'f']
它可以與index()函數結合使用,用index()獲取元素位置,然後用pop()刪除
7、index()函數
>>> test = ["a","b","c","d","e","f"]
>>> test.index("c")
2
>>> test = ["a","b","c","d","e","f"]
>>> test.pop(test.index("b")) # 結合pop()刪除元素b
'b'
>>> test
['a', 'c', 'd', 'e', 'f']